Python Strings #
Assign strings using double or single quotes. If string contains a single quote, then use double quotes.
message = 'hello world'
Triple quotes for multiple lines.
long_message = """
Super long
string in a variable
spread across multiple lines.
"""
Quick reference #
Some common string methods.
Method | Description | Example Input | Example Output |
---|---|---|---|
str() |
Convert to string | str(1) |
"1" |
len() |
Count the number of characters in a string | len("Bob") |
3 |
.lower() |
Lowercase everything | "BOB".lower() |
bob |
.upper() |
Uppercase everything | "bob".upper() |
BOB |
.count() |
Count the presence of a string in another string | "hello hello".count("hello") |
2 |
.find() |
Find first index for where some character or string appears. If the thing being sought isn’t present, return -1 . |
"Why hello there".find("hello") |
4 |
<string>.replace(<what to replace>, <replacement>) |
Replace stuff | "Why hello there".replace("there", "you") |
'Why hello you' |
<string>.zfill(<number of desired digits>) |
Pad with zeros | str(50).zfill(5) |
'00050' |
Combining strings #
<string> + " " + <another string>
Or use formatting (formatted string).
message = '{} , {}'.format(<string1>, <string2>)
Or with fstring
, where variables can be inserted directly between curly braces.
f'{<string1>}, {<string2>}.'
Can modify in place with fstring. For example:
f'{<string1>}, {<string2>.upper()}.'