Strings are immutable, indexable, iterable sequences. String interning creates surprising is results. f-strings have edge cases. Let's test you.
s = "hello" s[0] = "H"
TypeError: 'str' object does not support item assignment. To "modify" a string, you must create a new one: s = "H" + s[1:] or use s.replace("h", "H", 1).s = "hello" s = s.upper() print(s)
.upper() returns a new string — it doesn't modify the original. The old "hello" string is abandoned and s is rebound to the new "HELLO" string. This is how all string methods work — they always return new strings.a = "hello" b = "hello" print(a == b) print(a is b) c = "hello world" d = "hello world" print(c is d) # may vary
"hello" is interned — a is b is True. Strings with spaces like "hello world" may not be interned — c is d may be False. Never rely on string identity — always use ==.print("abc" * 3) print("-" * 20) print("ab" * 0)
"abc" * 3 produces "abcabcabc". "-" * 20 creates a separator line. "ab" * 0 returns an empty string (not an error). Multiplying by a negative also gives empty string.parts = ["a", "b", "c"] result = ",".join(parts) print(result) print(type(result))
separator.join(iterable) joins the elements with the separator between each pair. It returns a single string. This is much more efficient than concatenation in a loop (s += item). Always use join() when building strings from a list.s = " hello world " print(s.strip()) print(s.lstrip()) print(s.split()) print(s.split(" "))
.strip() removes leading/trailing whitespace. .lstrip() only left side. .split() with no argument splits on ANY whitespace and discards empty strings — the smart default. .split(" ") splits on exact single space, preserving empty strings between consecutive spaces — rarely what you want.name = "Alice" score = 95.678 print(f"Hello, {name}!") print(f"Score: {score:.2f}") print(f"{2 ** 10}") # expression in f-string
{} at runtime. :.2f is a format spec — 2 decimal places, rounded. 95.678 rounds to 95.68. Any valid Python expression can go inside the braces — including 2**10.x = 42 print(f"{x=}") # = inside f-string (Python 3.8+)
= specifier in an f-string (Python 3.8+) prints both the variable name and its value. f"{x=}" produces x=42. Extremely useful for debugging: print(f"{my_var=}") shows the variable name alongside its value without extra typing.s = "hello" print("e" in s) print(s.startswith("he")) print(s.endswith("LO")) print(s.find("l")) print(s.find("z"))
in checks substring membership (case-sensitive). .startswith() and .endswith() are case-sensitive — "LO" ≠ "lo". .find() returns the index of the first occurrence, or -1 if not found (unlike .index() which raises ValueError if not found).s = "abcabc" print(s.replace("a", "X")) print(s.replace("a", "X", 1)) print(s)
.replace(old, new) replaces ALL occurrences. .replace(old, new, count) replaces at most count occurrences. Crucially, the original string s is UNCHANGED — .replace() returns a new string. Never forget: strings are immutable.s = "Python" print(s[2:5]) print(s[-1]) print(s[::-1])
s[2:5] → "tho" (indices 2,3,4). s[-1] → "n" (last). s[::-1] reverses the string → "nohtyP". String slicing works exactly like list slicing.print("{}".format(42)) print("{0} {1} {0}".format("a", "b")) print("{name}".format(name="Alice"))
.format() is the older string formatting method (pre f-strings). {} = positional. {0}, {1} = index-based. {name} = keyword-based. Index-based allows reuse ({0} appears twice). f-strings are preferred in modern Python but .format() is still widely used.result = "" for i in range(5): result += str(i) print(result)
+= in a loop works but is inefficient — each iteration creates a new string (since strings are immutable). For large loops, "".join(str(i) for i in range(5)) is much faster — it builds the string once. This is a classic performance pitfall.s = "hello" print(list(s)) print(len(s)) for c in s: print(c, end="-")
list(s) converts to a list of individual characters. len(s) counts characters. A for loop iterates character by character. print(end="-") uses "-" as the line terminator instead of newline.s = " hello " print(s.strip() == "hello") print(s.strip("h elo"))
.strip() with no args strips whitespace. .strip("h elo") strips any characters in the given set from both ends — not the substring "h elo". The set is {h, space, e, l, o}. All characters in " hello " are in that set, so everything is stripped → "".s = "hello" print(s.center(11)) print(s.center(11, "*")) print(s.ljust(10, ".")) print(s.rjust(10, "."))
.center(width, fill) centers the string in a field of given width, padding with the fill character. .ljust() left-justifies (pads right). .rjust() right-justifies (pads left). These are useful for formatting tabular output. Default fill is a space.