Skip to content

String Operations

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.

name = " Alice Smith "
print(name.strip()) # "Alice Smith" -- removes leading/trailing whitespace
print(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 = 30
message = f"Name: {name.strip()}, Age: {age}" # f-strings for formatting
print("cat" in "concatenate") # True -- substring check
print("Hello".replace("H", "J")) # "Jello" -- returns a new string

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 result
print(text) # "HELLO"
  1. Why doesn’t my_string.upper() change my_string in place?

    AnswerStrings are immutable in Python β€” every string method returns a new string rather than mutating the original.
  2. What does "a-b-c".split("-") return?

    Answer['a', 'b', 'c']
  3. What’s the modern, preferred way to embed variables inside a string?

    Answerf-strings β€” e.g. f"Hello, {name}!" β€” they're more readable than .format() or %-formatting.