What is a string?
A string is a sequence of charactersβletters, numbers, spaces, and symbolsβwrapped in quotes. In Python, strings are immutable, meaning once created, they cannot be changed. Every operation on a string produces a new string.
Strings are everywhere: customer names in a banking database, M-Pesa transaction receipts, SMS messages, email addresses. Knowing how to clean, format, and extract data from strings is essential for any programmer handling real data.
Three ways to create strings:
name = "Arjun" # Single line, double quotes
message = 'Hello' # Single quotes work too
bio = """Multi-line
text here""" # Triple quotes
String literals & escape characters
You can create strings with single quotes, double quotes, or triple quotes. Triple quotes allow multi-line strings. Within a string, escape characters like \n, \t, and \\ represent special values.
Standard choice
"Hello, Nairobi"
Most common in Python code.
Also valid
'Same result'
Use when string contains double quotes.
Multi-line strings
"""Line 1
Line 2"""
Preserves newlines and indentation.
\n = newline
"Line1\nLine2"
Insert a line break in a single-line string.
\t = tab
"Name\tAge"
Horizontal indentation.
\\ = backslash
"C:\\Users"
To include a literal backslash.
Real scenario: SouthBank India KYC cleanup
SouthBank India processes hundreds of KYC (Know Your Customer) forms daily. Customer names arrive with inconsistent spacing, mixed case, and extra whitespace. Before storing in the database, names must be cleaned: spaces trimmed, case standardized, and formatted for display.
String indexing & slicing
Every character in a string has an index, starting at 0. You can access single characters or extract substrings using slice notation: string[start:end]. Remember: the end index is exclusive.
Full name: Priya Singh First name: Priya Last name: Singh Name length: 11
Common string methods
Strings have built-in methods that perform common operations. Here are the most useful ones for data cleanup:
Original: ' ARJUN PATEL ' Cleaned: 'ARJUN PATEL' Lowercase: 'arjun patel' Replaced: 'ARJUN VERMA' Starts with ARJUN? True Ends with VERMA? True
Split & join β breaking and building strings
split() breaks a string into a list using a delimiter. join() does the reverse, combining a list of strings with a separator. These are essential for formatting data.
Original: PRIYA SINGH As list: ['PRIYA', 'SINGH'] Reformatted: SINGH, PRIYA Phone (raw): 91-9876-543-210 Phone (clean): 919876543210
F-strings β the modern way to format
F-strings (formatted string literals) are the cleanest, fastest way to embed variables in text. Prefix a string with f and wrap variables in {}. This is the style recommended by PEP 8.
ββββββββββββββββββββββββββ β M-PESA RECEIPT β ββββββββββββββββββββββββββ Transaction ID: MH2K3L4P5 Sender: Aisha Amount: KSh 2,500 Available balance: KSh 8,750.50 Reference: +254712345678 Sent on: 2024-01-15 14:32:00 Cost: βΉ450, GST: βΉ81.00, Total: βΉ531.00
String immutability
Strings are immutable in Python. This means you cannot change a character in place. Every operation that appears to "modify" a string actually creates a new one. This is important for understanding how strings behave in memory and for writing efficient code.
Example: name = "ARJUN" creates a string object. When you call name.lower(), it returns a new string "arjun" β it does not change the original.
name = "ARJUN"
# name[0] = 'a' would raise: TypeError
new_name = name.lower() # Creates a new string
name # Still "ARJUN"
Also used in
Banking & Finance
Parsing account holder names, scrubbing PAN/Aadhaar numbers, formatting transaction IDs for compliance.
Fintech & Mobile Money
Formatting M-Pesa receipts, parsing SMS confirmations, extracting phone numbers from transaction logs.
Data Engineering
Cleaning messy CSV imports, normalizing company names, extracting fields from unstructured logs.
How AI uses this
Natural Language Processing (NLP)
Every NLP model starts by tokenizing text β splitting raw strings into words or subwords. Models like BERT, GPT, and Hugging Face transformers apply string operations millions of times per training step. When you clean customer feedback or prepare training data, you're doing what these models do internally.
π― Mini Challenge
You have a raw phone list from an M-Pesa CSV export:
" AISHA ,254712345678 "
Split by comma to extract name and phone. Clean both: strip spaces, convert name to title case (first letter uppercase), and verify the phone starts with "254" (Kenya code). Format a clean record: "Aisha | +254712345678"
raw = " AISHA ,254712345678 "
parts = raw.split(",") gives you a list of 2 elements. Then parts[0].strip() and parts[1].strip().
Use .title() for the name, check .startswith("254") for the phone.
Use an f-string to format the final record.
π€ Interview Questions
.lower() or .replace()) returns a new string. This is different from lists, which are mutable and can be modified in place. Immutability makes strings safe to use as dictionary keys and in sets.find() returns -1 if not found. index() raises a ValueError if not found. Use find() when you're not sure the substring exists and want to handle the "not found" case gracefully. Use index() when you expect it to be there and want an error to surface bugs.{}. Example: f"Total: βΉ{cost * 1.18:.2f}". The older .format() and %-formatting still work but are slower and harder to read. PEP 8 recommends f-strings for new code. Use the older styles only if you need Python 3.5 compatibility."hello world".split() (no argument) splits on any whitespace (spaces, tabs, newlines) and removes empty strings from the result. This is different from .split(" ") which splits on a single space and keeps empty strings. Always use .split() with no argument for robust whitespace handling, especially with messy real-world data..join() on lists instead.π§ Quick Quiz
"hello"[1:4] return?"hello world".split() return?"HELLO".lower() return?" hello ".strip() return?π Quick Cheatsheet
| Operation | Syntax | Returns | Example |
|---|---|---|---|
| Indexing | s[0] | Single character | "hello"[0] β "h" |
| Slicing | s[1:4] | Substring | "hello"[1:4] β "ell" |
| Length | len(s) | Integer | len("hello") β 5 |
| Lowercase | s.lower() | String | "HELLO".lower() β "hello" |
| Uppercase | s.upper() | String | "hello".upper() β "HELLO" |
| Title case | s.title() | String | "hello world".title() β "Hello World" |
| Strip spaces | s.strip() | String | " hello ".strip() β "hello" |
| Replace | s.replace(old, new) | String | "hello".replace("l", "L") β "heLLo" |
| Split | s.split(delim) | List | "a,b,c".split(",") β ["a", "b", "c"] |
| Join | delim.join(list) | String | ",".join(["a", "b"]) β "a,b" |
| Find | s.find(substr) | Integer | "hello".find("l") β 2 (or -1) |
| Starts with | s.startswith(pre) | Boolean | "hello".startswith("he") β True |
| Ends with | s.endswith(suf) | Boolean | "hello".endswith("lo") β True |
| Count | s.count(substr) | Integer | "hello".count("l") β 2 |
| F-string | f"{variable}" | String | f"Age: {25}" β "Age: 25" |
β οΈ Common Mistakes
s[0] = "x". It raises TypeError. Instead, reassign: s = "x" + s[1:] or use a list, which is mutable.s[0:3] returns indices 0, 1, 2βnot 0, 1, 2, 3. The end index is exclusive. To get the first 3 characters, write s[:3] or s[0:3].== instead of in for substring searchif "hello" in text: not if text == "hello":. The first checks containment, the second checks equality..strip() first: if name.strip().lower() == "arjun":. Spaces cause silent bugs in data validation.β¦ Key Takeaways
- Strings are immutable β operations on them create new strings, never modify in place
- Use indexing (
s[0]) for single characters and slicing (s[1:4]) for substrings - Essential methods for real data:
.strip(),.lower(),.upper(),.replace(),.split(),.join() - F-strings are the modern, preferred way to format β clean, fast, and support expressions
.find()returns -1 if not found;.index()raises an exception β choose based on your error handling needs- Always
.strip()user input before validation to avoid whitespace bugs in databases
You've mastered string methods.
Now clean real customer data.
Join the Best AI Program: The AI-Era Analyst β 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst β