Python Atlas
Foundations

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]) # nohtyp

Slices 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"))             # 2

find 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-methods

Calling 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,567

Use 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))              # 7

Other foundational built-ins:

  • type and isinstance inspect types.
  • int, float, str, bool, list, tuple, dict, and set construct or convert values.
  • range produces an arithmetic sequence for iteration.
  • enumerate pairs values with positions.
  • zip combines iterables position by position.
  • map and filter lazily transform or select values.
  • print writes output and input reads one line of text.
  • help displays documentation in an interactive session.

Do not name variables str, list, sum, or other built-in names:

# list = [1, 2]  # shadows the list constructor

Text 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 rebind name.
  • Using split(" ") when arbitrary whitespace should be handled by split().
  • Calling sum on strings; use "".join(parts) instead.
  • Shadowing a built-in with a variable name.
  • Assuming round is 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 in for presence, find for a position with a sentinel, and index when absence is an error.
  • Use join for many string pieces; repeated + is acceptable for a few literals.
  • Normalize external text with strip and, when case-insensitive comparison is required, casefold().

Practice

  1. Normalize " PyThOn " to "python".
  2. Split "red,green,blue" and join it as "red | green | blue".
  3. Print a price with two decimal places and thousands separators.
  4. 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

Strings and Built-ins

1Given `word = 'python'`, what does `word[1:4]` produce?
2Which call best splits text on arbitrary runs of surrounding whitespace?