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.

Double Quotes

Standard choice

"Hello, Nairobi"

Most common in Python code.

Single Quotes

Also valid

'Same result'

Use when string contains double quotes.

Triple Quotes

Multi-line strings

"""Line 1
Line 2"""

Preserves newlines and indentation.

Escape Char

\n = newline

"Line1\nLine2"

Insert a line break in a single-line string.

Escape Char

\t = tab

"Name\tAge"

Horizontal indentation.

Escape Char

\\ = backslash

"C:\\Users"

To include a literal backslash.

Real scenario: SouthBank India KYC cleanup

🏦
Business case
Customer database import with dirty data

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.

β‚Ή4.2M
Daily transactions
2,847
KYC forms
35%
Manual entry errors

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.

Indexing customer names code1
Output:
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:

Cleanup methods: strip, lower, upper, replace code2
Output:
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.

Reformatting data: split then join code3
Output:
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 SMS receipt formatting with f-strings code4
Output:
╔════════════════════════╗
β•‘   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.

SouthBank India Account numbers KYC validation

Fintech & Mobile Money

Formatting M-Pesa receipts, parsing SMS confirmations, extracting phone numbers from transaction logs.

M-Pesa Kenya SMS parsing Receipt formatting

Data Engineering

Cleaning messy CSV imports, normalizing company names, extracting fields from unstructured logs.

CSV parsing Data cleaning Log analysis

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.

Tokenization Text cleaning BERT GPT Hugging Face

🎯 Mini Challenge

Clean and format a customer phone list

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

No. Strings are immutable. Once created, you cannot change individual characters. Every string operation (like .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.
Both search for a substring. 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.
F-strings (Python 3.6+) are faster, more readable, and allow expressions inside {}. 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.
Immutability allows Python to cache frequently used strings (like single characters) and reuse them, saving memory. It also makes strings safe to use as dictionary keys and in sets β€” mutable objects cannot be keys because their hash value could change. In concurrent code, immutability eliminates race conditions since multiple threads can safely share the same string without locks. The trade-off: creating lots of modified strings (via concatenation in loops) is slow β€” always use .join() on lists instead.

🧠 Quick Quiz

Question 1 of 5
What does "hello"[1:4] return?
Question 2 of 5
What does "hello world".split() return?
Question 3 of 5
What does "HELLO".lower() return?
Question 4 of 5
What does " hello ".strip() return?
Question 5 of 5
Which is the recommended modern way to format strings in Python 3.6+?
0
/5

πŸ“‹ Quick Cheatsheet

OperationSyntaxReturnsExample
Indexings[0]Single character"hello"[0] β†’ "h"
Slicings[1:4]Substring"hello"[1:4] β†’ "ell"
Lengthlen(s)Integerlen("hello") β†’ 5
Lowercases.lower()String"HELLO".lower() β†’ "hello"
Uppercases.upper()String"hello".upper() β†’ "HELLO"
Title cases.title()String"hello world".title() β†’ "Hello World"
Strip spacess.strip()String" hello ".strip() β†’ "hello"
Replaces.replace(old, new)String"hello".replace("l", "L") β†’ "heLLo"
Splits.split(delim)List"a,b,c".split(",") β†’ ["a", "b", "c"]
Joindelim.join(list)String",".join(["a", "b"]) β†’ "a,b"
Finds.find(substr)Integer"hello".find("l") β†’ 2 (or -1)
Starts withs.startswith(pre)Boolean"hello".startswith("he") β†’ True
Ends withs.endswith(suf)Boolean"hello".endswith("lo") β†’ True
Counts.count(substr)Integer"hello".count("l") β†’ 2
F-stringf"{variable}"Stringf"Age: {25}" β†’ "Age: 25"

⚠️ Common Mistakes

Forgetting that strings are immutable
You cannot do s[0] = "x". It raises TypeError. Instead, reassign: s = "x" + s[1:] or use a list, which is mutable.
Off-by-one in slicing
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].
Using == instead of in for substring search
To check if a substring exists, use if "hello" in text: not if text == "hello":. The first checks containment, the second checks equality.
Not removing whitespace before validation
If comparing strings from user input, always .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
Africa & India's Best AI Academy
πŸ€– AI-first πŸŽ“ Placement Assistance

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 β†’