String Operations
String Operations
Section titled βString OperationsβWhat it means
Section titled βWhat it meansβStrings in Python are immutable sequences of characters. Every βmodificationβ (like .upper() or .replace()) actually returns a new string rather than changing the original. Python offers a rich set of built-in methods for searching, transforming, splitting, and formatting text.
Examples
Section titled βExamplesβname = " Alice Smith "
print(name.strip()) # "Alice Smith" -- removes leading/trailing whitespaceprint(name.strip().lower()) # "alice smith"print(name.strip().split(" ")) # ['Alice', 'Smith']print("-".join(["a", "b", "c"])) # "a-b-c"print("world" in "hello world") # True
age = 30message = f"Name: {name.strip()}, Age: {age}" # f-strings for formatting
print("cat" in "concatenate") # True -- substring checkprint("Hello".replace("H", "J")) # "Jello" -- returns a new stringCommon mistake
Section titled βCommon mistakeβAssuming string methods modify the string in place β since strings are immutable, you must capture the return value, or the change is silently discarded.
text = "hello"text.upper() # does nothing to `text` -- return value is discarded!print(text) # still "hello"
text = text.upper() # correct -- reassign the resultprint(text) # "HELLO"Quick practice
Section titled βQuick practiceβ-
Why doesnβt
my_string.upper()changemy_stringin place?Answer
Strings are immutable in Python β every string method returns a new string rather than mutating the original. -
What does
"a-b-c".split("-")return?Answer
['a', 'b', 'c'] -
Whatβs the modern, preferred way to embed variables inside a string?
Answer
f-strings β e.g.f"Hello, {name}!"β they're more readable than.format()or%-formatting.