Strings

Strings are immutable sequences of Unicode characters. They offer rich methods for searching, slicing, formatting and manipulation.

Details

Strings can be created with single, double, or triple quotes. They are indexed (0-based) and support slicing s[start:stop]. Because strings are immutable, most operations return new strings. Common methods: .upper(), .lower(), .strip(), .split(), .join(), .replace().

Examples

s = " Hello, World!  "
print(s.strip())
print(s[1:6])
parts = "a,b,c".split(",")
print(parts)
print(" - ".join(parts))
name = "khushi"
print(name.title())

Useful methods (quick)

MethodPurpose
split()Split string into list by separator
join()Join iterable into a single string
replace()Replace substring occurrences
strip()Remove leading/trailing whitespace

Common mistakes

  • IndexError when accessing out-of-range indices.
  • Trying to mutate a string (e.g., s[0] = 'A' — raises TypeError).
  • Forgetting to strip newline when comparing user input.

Exercises

  1. Reverse a string using slicing.
  2. Given a CSV string, split it and join it with semicolons.
  3. Write a function that capitalizes each word in a sentence (title case).

Next steps

Move to String Formatting and Regular Expressions for text processing and pattern matching.