Most programs handle a lot of text: names, addresses, messages, file contents. In Python, text is stored as a string (str). Python strings come with dozens of built-in tools for cleaning, searching and formatting text, and learning the common ones saves you a lot of work. You met strings briefly in Python Data Types; this lesson goes deeper.
Creating Python strings
Put text inside single quotes ('…') or double quotes ("…"). Use the other kind of quote when the text itself contains one, as in "Raja's Bakery". Triple quotes ("""…""") let a string run over several lines.
Inside a string, a backslash starts an escape sequence: \n is a new line, \t a tab, \" a double quote and \\ a real backslash. A raw string, written r"…", turns escapes off, which is useful for Windows paths such as r"C:\new\data".
shop = "Raja's Bakery"
print(shop)
print("Menu:\n\tPuffs\n\tCake")
address = """No. 12, Gandhi Road
Tiruppur 641601"""
print(address)
print(r"C:\new\data")Raja's Bakery Menu: Puffs Cake No. 12, Gandhi Road Tiruppur 641601 C:\new\data
Indexing and slicing
A string is a sequence of characters, and each one has a position called an index. Counting starts at 0. Negative indexes count from the end, so -1 is the last character.
A slice takes part of a string: text[start:stop] gives the characters from start up to, but not including, stop. Leave out start to begin at the beginning, or stop to go to the end. A third number sets a step, so [::-1] walks backwards and reverses the string.
city = "Bengaluru"
print(city[0])
print(city[-1])
print(city[0:5])
print(city[5:])
print(city[:3].upper())
print(city[::-1])
print(len(city))B u Benga luru BEN urulagneB 9
Tip: A slice never raises an error for positions that are too large: city[5:100] simply returns "luru". A single index that is too large, such as city[20], does raise an IndexError.
Strings cannot be changed
Python strings are immutable: once created, a string never changes. city[0] = "b" gives a TypeError. Every string method therefore returns a new string, and you must store it if you want to keep the result, for example name = name.strip(). Forgetting to assign the result is one of the most common beginner mistakes.
Useful string methods
| Method | What it returns |
|---|---|
s.upper(), s.lower(), s.title() | The text in upper, lower or title case |
s.strip() | The text without spaces (and new lines) at both ends |
s.replace(old, new) | The text with every old replaced by new |
s.split(sep) | A list of pieces, cut wherever sep appears |
sep.join(items) | One string made by joining a list with sep between items |
s.find(sub) | The index of the first match, or -1 if not found |
s.count(sub) | How many times sub appears |
s.startswith(x), s.endswith(x) | True or False |
To check whether one string contains another, use the in operator: "pur" in "Tiruppur" is True. All comparisons are case-sensitive, which is why cleaning text with strip() and lower() before comparing is a good habit.
raw_name = " kavya SRINIVASAN "
name = raw_name.strip().title()
print(name)
print(" ".join(name.split()))
phone = "98400-12345"
print(phone.replace("-", ""))
csv_line = "Idli,Dosa,Pongal,Vada"
dishes = csv_line.split(",")
print(dishes)
print(" | ".join(dishes))
email = "[email protected]"
print(email.endswith(".com"), "@" in email, email.find("@"))
print("banana".count("a"))Kavya Srinivasan Kavya Srinivasan 9840012345 ['Idli', 'Dosa', 'Pongal', 'Vada'] Idli | Dosa | Pongal | Vada True True 5 3
Look at the first two lines of output. strip() only trims the ends, so the extra spaces in the middle of the name survive. split() with no argument splits on any run of spaces, tabs or new lines and drops empty pieces, so joining the pieces back with a single space is a neat way to tidy messy input. Also notice how methods can be chained: raw_name.strip().title() runs strip() first and then calls title() on its result.
Formatting with f-strings
An f-string has an f before the opening quote. Anything inside { } is evaluated and placed in the text. After a colon you can add a format specification to control how the value looks.
| Format | Meaning | Result |
|---|---|---|
{price:.2f} | Two decimal places | 1499.00 |
{amount:,} | Comma thousands separator | 1,250,000 |
{name:<10} | Left-align in 10 characters | Ravi |
{qty:>5} | Right-align in 5 characters | 3 |
{score:.0%} | As a percentage | 85% |
{total=} | Show the expression and its value (handy for debugging) | total=450 |
items = [("Filter coffee", 2, 40), ("Masala dosa", 1, 95), ("Kesari", 3, 35)]
print(f"{'Item':<15}{'Qty':>4}{'Amount':>10}")
total = 0
for name, qty, price in items:
amount = qty * price
total += amount
print(f"{name:<15}{qty:>4}{amount:>10.2f}")
print(f"{'Total':<19}{total:>10.2f}")
savings = 1250000
print(f"Savings: ₹{savings:,}")
print(f"{total=}")Item Qty Amount Filter coffee 2 80.00 Masala dosa 1 95.00 Kesari 3 105.00 Total 280.00 Savings: ₹1,250,000 total=280
The receipt uses a for loop, which you will learn in Python Loops. Focus on the f-strings: the widths line the columns up neatly.
Watch out: The , format uses international grouping (1,250,000), not the Indian lakh style (12,50,000). Python has no built-in format code for the lakh style, so for Indian-style display you need a small helper function or a third-party library.
