Manipulating Text With String Functions
Text is everywhere — usernames, addresses, JSON payloads, emails, log lines. Python's str type comes with a rich library of built-in methods that make text manipulation effortless. In this chapter you'll meet the most useful string functions and the idioms professional Python developers rely on every day.
Overview
Case Conversion
upper, lower, title, swapcase, capitalize.
Slicing & Indexing
Access characters or substrings with s[i], s[start:stop:step].
Search Tools
find, index, count, startswith, endswith.
Split & Join
Parse CSVs and join lists into delimited strings.
Powerful Formatting
f-strings, format(), padding, alignment, number formatting.
Syntax
- Strings can be created with single, double, or triple quotes.
- Use
'string'.method()— most methods return a new string. - Use f-strings (
f"...{var}...") for readable formatting. - Strings are immutable — methods always produce a new string, never modify in place.
s = "Hello, Python!"
print(s.upper()) # HELLO, PYTHON!
print(s.lower()) # hello, python!
print(s.replace("Hello", "Hi"))
print(s.split(","))
print("-".join(["a", "b", "c"]))
print(f"Length is {len(s)}")
Detailed Explanation
- Strings are immutable: Once created, a string cannot be changed.
s.upper()returns a new string; the original is untouched. This guarantees thread-safety and predictable behaviour. - Case methods:
upper(),lower(),title(),capitalize(),swapcase()handle every case-conversion need. - Searching:
find()andindex()locate substrings;find()returns-1if not found,index()raises aValueError.inis the cleanest membership test. - Splitting and joining:
split(sep)breaks a string into a list.'sep'.join(list)joins a list back into a string. Together they are your CSV/log parser. - Replacing:
replace(old, new, count)creates a new string with substitutions. For regex patterns use theremodule. - Formatting: f-strings are fastest and most readable.
.format()works on older Python.%-formattingis legacy.
Code Examples
s = "Python Programming" print(s.upper()) print(s.lower()) print(s.swapcase())
python programming
pYTHON pROGRAMMING
s = "Programming" print(s[:7]) print(s[7:]) print(s[::-1])
ming
gnimmargorP
csv = "Anu,Riya,Sam,Ankit"
names = csv.split(",")
print(names)
print(" | ".join(names))
Anu | Riya | Sam | Ankit
s = " Hello, World! "
print(s.strip())
print(s.replace("World", "Python"))
Hello, Python!
s = "banana"
print(s.count("a"))
print(s.find("na"))
print("ban" in s)
2
True
name, age = "Ankit", 25
print(f"{name} is {age} years old")
print(f"Pi ≈ {3.14159:.2f}")
print(f"|{name:>10}|")
Pi ≈ 3.14
| Ankit|
Real-World Use Cases
Email Parsing
Split addresses on '@' to extract domain and username.
CSV Processing
Use split(',') or csv module to read records.
Web Scraping
Clean scraped text — strip, lower, replace HTML entities.
Internationalisation
Normalise Unicode strings before storing or comparing.
Form Validation
Check email/phone formats with startswith, endswith, and regex.
Document Search
Use find() and count() to locate keywords in texts.
Notes & Pro Tips
- Strings are immutable — chain methods:
s.strip().lower().replace(' ', '_'). - Use
infor membership tests — it's clearer thanfind() != -1. - Prefer f-strings for formatting — they are fast, readable, and support expressions.
- Use
str.maketrans()+translate()for high-performance bulk replacements. - Use raw strings
r"..."when writing regex patterns or Windows paths. - For complex search/replace, use the
remodule — but reach for str methods first.
Common Mistakes
- Trying to mutate:
s[0] = 'A'raisesTypeError— strings are immutable. - String concatenation in loops: use
''.join(...)or a list buffer for speed. - Comparing with == on different cases: normalise both sides with
lower()first. - Off-by-one in slicing:
s[0:3]includes indices 0,1,2 — not 3. - Confusing find() and index(): the former returns -1 on miss; the latter raises.
- Forgetting
strip(): trailing whitespace in user input ruins comparisons.
Practice Problems
- Problem 1: Reverse a given string without using slicing.
- Problem 2: Count the number of vowels, consonants, digits and special characters in a string.
- Problem 3: Check if a string is a palindrome (case-insensitive).
- Problem 4: Replace every occurrence of a vowel in a string with '*'.
- Problem 5: Split a sentence into words and print the longest word.
- Problem 6: Convert a CSV line like
'Riya, 22, Bangalore'into a dictionary with keys name/age/city.
Interview Questions
- Q1. Why are strings immutable in Python?
- Q2. What is the difference between
find()andindex()? - Q3. Compare f-strings,
.format(), and%-formatting. - Q4. How would you reverse a string in Python?
- Q5. Why is repeated string concatenation slow, and how do you fix it?
- Q6. What is the time complexity of
str.find()?
Frequently Asked Questions
- Q1: Why are strings immutable?
Immutability allows Python to cache small strings, hash them safely for use as dict keys, and provides thread-safety guarantees. - Q2: How do I reverse a string?
Use slicing: s[::-1]. It's the most Pythonic and efficient method. - Q3: How do I check if a substring exists?
Use the in operator: if 'sub' in s. It returns a clean boolean. - Q4: What are f-strings?
Formatted string literals (Python 3.6+). Prefix the string with f and embed expressions inside {}. They are fast and readable. - Q5: How do I remove leading/trailing spaces?
Use s.strip(). For one side only, use lstrip() or rstrip(). - Q6: How do I split on multiple delimiters?
Use re.split(r'[,; ]+', s) — the standard re module handles complex separators.
Summary
Python's string functions are short, expressive, and surprisingly powerful. Once you've internalised the case-converters, slicing, split/join, replace, and f-strings, you can express almost any text transformation in a single line. Strings being immutable means safety and clarity — every method returns a fresh result you can chain confidently.
Continue Learning
Previous
Go to Previous Chapter