Strings Deep Dive
Strings are sequences of characters. We introduced them earlier; now let's go deeper into string methods, formatting, and manipulation.
Common String Methods
- `upper()`, `lower()` – change case
- `strip()` – remove leading/trailing whitespace
- `split(sep)` – split into list
- `join(iterable)` – join list into string
- `replace(old, new)` – replace substrings
- `find(sub)` – return index of first occurrence (‑1 if not found)
- `count(sub)` – count occurrences
- `startswith(prefix)`, `endswith(suffix)`
s = " Hello, World! "
print(s.strip()) # "Hello, World!"
print(s.split(",")) # [' Hello', ' World! ']
print("-".join(["a","b","c"])) # "a-b-c"
print(s.replace("World", "Python"))
String Formatting
Python offers several ways to format strings. The modern approach is f‑strings (Python 3.6+).
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
# You can include expressions
print(f"{age * 2}")
String Slicing and Immutability
Strings are immutable; slicing creates new strings.
word = "Python"
print(word[1:4]) # "yth"
print(word[::-1]) # reversed
Two Minute Drill
- String methods: upper, lower, strip, split, join, replace, find, count.
- Use f‑strings for formatting: `f"{var}"`.
- Strings are immutable; operations create new strings.
- Slicing works similarly to lists.
- Strings are central to text processing.
Need more clarification?
Drop us an email at career@quipoinfotech.com
