String Functions In Python — PBA Institute Tutorial
Chapter 09 · Python Programming Series
12 min read Beginner

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.
String Functions — Syntax
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() and index() locate substrings; find() returns -1 if not found, index() raises a ValueError. in is 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 the re module.
  • Formatting: f-strings are fastest and most readable. .format() works on older Python. %-formatting is legacy.

Code Examples

Example 1 — Case Methods
s = "Python Programming"
print(s.upper())
print(s.lower())
print(s.swapcase())
Output PYTHON PROGRAMMING
python programming
pYTHON pROGRAMMING
Example 2 — Slicing
s = "Programming"
print(s[:7])
print(s[7:])
print(s[::-1])
Output Program
ming
gnimmargorP
Example 3 — split() and join()
csv = "Anu,Riya,Sam,Ankit"
names = csv.split(",")
print(names)
print(" | ".join(names))
Output ['Anu', 'Riya', 'Sam', 'Ankit']
Anu | Riya | Sam | Ankit
Example 4 — Replace & Strip
s = "  Hello, World!  "
print(s.strip())
print(s.replace("World", "Python"))
Output Hello, World!
Hello, Python!
Example 5 — Count & Find
s = "banana"
print(s.count("a"))
print(s.find("na"))
print("ban" in s)
Output 3
2
True
Example 6 — f-string Formatting
name, age = "Ankit", 25
print(f"{name} is {age} years old")
print(f"Pi ≈ {3.14159:.2f}")
print(f"|{name:>10}|")
Output Ankit is 25 years old
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 in for membership tests — it's clearer than find() != -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 re module — but reach for str methods first.

Common Mistakes

  • Trying to mutate: s[0] = 'A' raises TypeError — 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() and index()?
  • 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

Next

Go to Next Chapter