f-strings (Formatted String Literals) syntax Copy
f"text {expression}" example Copy
name = "Alice"
balance = 1234.5
print (f"User: {name}" )
print (f"Balance: ${balance:,.2f}" )
print (f"{'centered':^20}" )output
User: Alice
Balance: $1,234.50
centered Note Since Python 3.12, f-strings can contain backslashes and nested quotes freely. You can also nest f-strings inside f-strings.
format string f-string string interpolation template string format number
syntax Copy
str.method()example Copy
email = " Alice@Example.COM "
print (email.strip().lower())
print ("hello world" .title())
print ("python" .startswith("py" ))
print ("2026-04-04" .replace("-" , "/" ))output
alice@example.com
Hello World
True
2026/04/04Note String methods always return new strings since strings are immutable. Chain methods for compact transformations.
string methods strip whitespace lowercase uppercase replace text startswith
syntax Copy
string [start:stop:step]example Copy
word = "pythonic"
print (word[0 :4 ])
print (word[-4 :])
print (word[::2 ])
print (word[::-1 ])output
pyth
onic
ptoi
cinohtypNote Slicing never raises IndexError, even if indices exceed the string length. Negative step reverses direction.
slice string substring reverse string string indexing
syntax Copy
"" "text
spanning lines" "" example Copy
query = "" "
SELECT name, email
FROM users
WHERE active = true
" "" .strip()
print (query)output
SELECT name, email
FROM users
WHERE active = trueNote Triple-quoted strings preserve all whitespace and newlines. Use textwrap.dedent() or .strip() to control leading/trailing space.
multiline string triple quotes long string heredoc
syntax Copy
r"text with \backslashes" example Copy
path = r"C:\Users\alice\docs"
pattern = r"\d{3}-\d{4}"
print (path)
print (pattern)output
C:\Users\alice\docs
\d{3}-\d{4}Note Raw strings treat backslashes as literal characters. Essential for regex patterns and Windows paths. A raw string cannot end with an odd number of backslashes.
raw string escape backslash regex string windows path
syntax Copy
str.encode(encoding)
bytes.decode(encoding)example Copy
text = "caf\u00e9"
encoded = text.encode("utf-8" )
print (encoded)
print (encoded.decode("utf-8" ))output
b'caf\xc3\xa9'
caf\u00e9Note UTF-8 is the default encoding. Use errors='ignore' or errors='replace' to handle characters that cannot be encoded in the target encoding.
encode string decode bytes utf-8 bytes to string string to bytes
syntax Copy
separator.join (iterable)
str.split(separator)example Copy
words = ["Python" , "is" , "great" ]
sentence = " " .join (words)
print (sentence)
csv_row = "alice,30,engineer"
fields = csv_row.split("," )
print (fields)output
Python is great
['alice', '30', 'engineer']Note split() with no arguments splits on any whitespace and removes empty strings. split(',') keeps empty strings between consecutive delimiters.
join list to string split string csv parse concatenate strings
syntax Copy
str.isdigit() / str.isalpha() / str.isalnum()example Copy
pin = "4821"
print (pin.isdigit())
print ("hello123" .isalnum())
print (" " .isspace())
print ("api" in "api_key_value" )output
True
True
True
TrueNote The 'in' operator checks for substring presence and is usually more practical than the .is*() family for real-world validation.
check if number check if letters string contains validate string