Strings and Built-ins
Create and transform Unicode text while using Python's essential built-in functions.
A string is an immutable sequence of Unicode characters. Text operations return new strings; they do not modify the original.
Creating strings
Single and double quotes are equivalent:
language = "Python"
message = 'She said "hello".'
path = r"C:\projects\demo"
multiline = """First line
Second line"""Normal strings interpret escapes such as \n and \t. Raw strings treat backslashes mostly
literally, which is useful for Windows paths and regular expressions. A raw string cannot end in
a single backslash.
Indexing and slicing
Indices begin at zero; negative indices count from the end:
word = "python"
print(word[0]) # p
print(word[-1]) # n
print(word[1:4]) # yth
print(word[:2]) # py
print(word[::2]) # pto
print(word[::-1]) # nohtypSlices exclude the stop index and tolerate out-of-range boundaries. Direct indexing does not:
word[99] raises IndexError.
Because strings are immutable, word[0] = "P" is invalid. Build a new value:
capitalized = "P" + word[1:]Essential string methods
raw = " Ada Lovelace "
clean = raw.strip()
print(clean.lower()) # ada lovelace
print(clean.upper()) # ADA LOVELACE
print(clean.startswith("Ada")) # True
print(clean.endswith("lace")) # True
print(clean.replace("Ada", "Augusta"))
print(clean.find("Love")) # 4
print(clean.count("a")) # 2find returns -1 when no match exists; index raises ValueError. Use in when only
presence matters.
Split text into a list and join strings with a separator:
record = "Ada,36,London"
fields = record.split(",")
print(fields) # ['Ada', '36', 'London']
slug = "-".join(["python", "string", "methods"])
print(slug) # python-string-methodsCalling split() without an argument handles runs of whitespace and ignores surrounding
whitespace.
Useful tests include isalpha(), isdigit(), isalnum(), and isspace(). Their definitions
follow Unicode rules, so they recognize more than ASCII characters.
Formatting with f-strings
F-strings embed expressions and support format specifications:
name = "Ada"
score = 93.456
count = 7
print(f"{name} scored {score:.1f}%")
print(f"{count:04d}") # 0007
print(f"{1234567:,}") # 1,234,567Use f-strings for readable application output. Use structured logging's parameter mechanism instead of eagerly formatted strings when a logging framework expects it.
Important built-in functions
Built-ins are always available without imports:
values = [8, 3, 11]
print(len(values)) # 3
print(min(values)) # 3
print(max(values)) # 11
print(sum(values)) # 22
print(sorted(values)) # [3, 8, 11]
print(any([False, True])) # True
print(all([True, True])) # True
print(round(3.14159, 2)) # 3.14
print(abs(-7)) # 7Other foundational built-ins:
typeandisinstanceinspect types.int,float,str,bool,list,tuple,dict, andsetconstruct or convert values.rangeproduces an arithmetic sequence for iteration.enumeratepairs values with positions.zipcombines iterables position by position.mapandfilterlazily transform or select values.printwrites output andinputreads one line of text.helpdisplays documentation in an interactive session.
Do not name variables str, list, sum, or other built-in names:
# list = [1, 2] # shadows the list constructorText versus bytes
str represents text; bytes represents raw byte values. Encode at an external boundary and
decode when bytes become text:
text = "café"
payload = text.encode("utf-8")
restored = payload.decode("utf-8")
print(payload) # b'caf\xc3\xa9'
print(restored) # caféKeep text as str inside normal application logic.
Common mistakes
- Concatenating text and numbers directly: use an f-string or explicit conversion.
- Forgetting that methods return new strings:
name.strip()alone does not rebindname. - Using
split(" ")when arbitrary whitespace should be handled bysplit(). - Calling
sumon strings; use"".join(parts)instead. - Shadowing a built-in with a variable name.
- Assuming
roundis suitable for exact financial rounding; binary floats are approximate.
Decision guidance
- Use methods for one text value and built-ins for general operations across types.
- Use
infor presence,findfor a position with a sentinel, andindexwhen absence is an error. - Use
joinfor many string pieces; repeated+is acceptable for a few literals. - Normalize external text with
stripand, when case-insensitive comparison is required,casefold().
Practice
- Normalize
" PyThOn "to"python". - Split
"red,green,blue"and join it as"red | green | blue". - Print a price with two decimal places and thousands separators.
- Given a sentence, count characters, words, and occurrences of
"python"ignoring case.
LEARNING RECORD
Finish this lesson
Mark it complete when you can explain the main decision without looking.
KNOWLEDGE CHECK