Strings In Depth
Quick Recap
You already know strings from Stage 1:
name = "Gagan"
message = 'Hello World'
But strings in Python are much more powerful than just storing text. Let's go deep.
Strings are Sequences
A string is actually a sequence of characters — just like a list but for text. This means everything you learned about indexing and slicing on lists works on strings too:
name = "Gagan" # 01234
print(name[0]) # G print(name[1]) # a print(name[-1]) # n (last character) print(name[1:4]) # aga (slicing) print(name[:3]) # Gag print(len(name)) # 5 (total characters)
Looping Through a String
name = "Gagan"
for char in name: print(char)
Output:
G
a
g
a
n
Strings are Immutable
Just like tuples, strings cannot be changed after creation:
name = "Gagan" name[0] = "K" # ERROR — strings are immutable
But you can create a new string from an old one:
name = "Gagan" new_name = "K" + name[1:] # 'K' + 'agan' print(new_name) # Kagan
String Methods — The Real Power
Python gives you dozens of built-in methods to work with strings. These are what you'll use every single day in real projects.
Case Methods
text = "Hello World"
print(text.upper()) # HELLO WORLD print(text.lower()) # hello world print(text.title()) # Hello World (first letter of each word capitalized) print(text.capitalize()) # Hello world (only first letter of string) print(text.swapcase()) # hELLO wORLD (swap upper/lower)
Real use case — case-insensitive comparison:
username = input("Enter username: ")
if username.lower() == "gagan": print("Welcome!")
Now it works whether user types "Gagan", "GAGAN", "gAgAn" — anything.
Whitespace Methods
text = " Hello World "
print(text.strip()) # "Hello World" (removes both sides) print(text.lstrip()) # "Hello World " (removes left side) print(text.rstrip()) # " Hello World" (removes right side)
Real use case — user input always has accidental spaces:
email = input("Enter email: ") email = email.strip().lower() # clean the input before using it
Always strip and lowercase user input before processing. This is standard practice.
Search Methods
text = "I love Python programming"
print(text.find("Python")) # 7 — index where it starts print(text.find("Java")) # -1 — not found, returns -1 print(text.count("o")) # 3 — how many times 'o' appears print(text.startswith("I love")) # True print(text.endswith("ing")) # True print("Python" in text) # True — simplest way to check
Replace Method
text = "I love Java. Java is great."
new_text = text.replace("Java", "Python") print(new_text) # I love Python. Python is great.
# Replace only first occurrence new_text2 = text.replace("Java", "Python", 1) print(new_text2) # I love Python. Java is great.
Original string is never changed — a new string is returned.
Split and Join — Very Important
split() — breaks a string into a list:
sentence = "I love Python programming" words = sentence.split() # split by space (default) print(words) # ['I', 'love', 'Python', 'programming'] print(words[2]) # Python
# Split by custom separator csv_data = "Gagan,22,Delhi,Python" parts = csv_data.split(",") print(parts) # ['Gagan', '22', 'Delhi', 'Python'] print(parts[0]) # Gagan print(parts[2]) # Delhi
join() — opposite of split, combines a list into a string:
words = ["I", "love", "Python"] sentence = " ".join(words) # join with space print(sentence) # I love Python
tags = ["python", "coding", "beginner"] result = ", ".join(tags) # join with comma and space print(result) # python, coding, beginner
path = ["home", "user", "documents"] file_path = "/".join(path) print(file_path) # home/user/documents
Check Methods
print("hello".isalpha()) # True — only letters print("hello123".isalpha()) # False — has numbers print("12345".isdigit()) # True — only digits print("hello123".isalnum()) # True — letters and numbers print(" ".isspace()) # True — only whitespace print("Hello World".istitle()) # True — title case
Real use case — validating user input:
age = input("Enter your age: ")
if age.isdigit(): age = int(age) print(f"Your age is {age}") else: print("Invalid input — please enter a number")
String Formatting — All Three Ways
You've been using f-strings. Let's see all three ways Python supports:
Way 1 — f-strings (Modern, Recommended)
name = "Gagan" age = 22 print(f"My name is {name} and I am {age} years old")
You can even put expressions directly inside:
price = 100 quantity = 3 print(f"Total: Rs.{price * quantity}") # Rs.300 print(f"Pi is approximately {22/7:.4f}") # Pi is approximately 3.1429
Way 2 — .format() method (Older)
name = "Gagan" age = 22 print("My name is {} and I am {} years old".format(name, age))
You'll see this in older code. f-strings are better but good to recognize this.
Way 3 — % operator (Very Old)
name = "Gagan" age = 22 print("My name is %s and I am %d years old" % (name, age))
Very old style — you'll rarely use this. Just recognize it if you see it.
Stick to f-strings — they're the cleanest and most modern.
f-string Formatting Options
You can control how values are displayed inside f-strings:
number = 1234567.89
print(f"{number:.2f}") # 1234567.89 (2 decimal places) print(f"{number:,.2f}") # 1,234,567.89 (comma separator) print(f"{number:.0f}") # 1234568 (no decimals, rounded)
# Padding and alignment name = "Gagan" print(f"{name:10}") # "Gagan " (10 chars, left aligned) print(f"{name:>10}") # " Gagan" (10 chars, right aligned) print(f"{name:^10}") # " Gagan " (10 chars, center aligned)
# Numbers with padding for i in range(1, 6): print(f"Item {i:02d}") # Item 01, Item 02... (pad with zeros)
Output of last loop:
Item 01
Item 02
Item 03
Item 04
Item 05
Multiline Strings
Use triple quotes for strings that span multiple lines:
message = """ Hello Gagan,
Welcome to our platform. Your account has been created successfully.
Thank you, Team Python """
print(message)
Output:
Hello Gagan,
Welcome to our platform.
Your account has been created successfully.
Thank you,
Team Python
Escape Characters
Special characters inside strings:
print("Hello\nWorld") # \n = new line print("Hello\tWorld") # \t = tab space print("He said \"Hello\"") # \" = double quote inside string print("C:\\Users\\Gagan") # \\ = backslash
Output:
Hello
World
Hello World
He said "Hello"
C:\Users\Gagan
Real World Example — User Registration Validator
def validate_username(username): username = username.strip() if len(username) < 3: return False, "Username too short (minimum 3 characters)" if len(username) > 20: return False, "Username too long (maximum 20 characters)" if not username.isalnum(): return False, "Username can only contain letters and numbers" return True, "Username is valid"
def validate_email(email): email = email.strip().lower() if "@" not in email: return False, "Email must contain @" if "." not in email: return False, "Email must contain a dot" return True, "Email is valid"
def validate_password(password): if len(password) < 8: return False, "Password too short (minimum 8 characters)" if password.isalpha(): return False, "Password must contain at least one number" if password.isdigit(): return False, "Password must contain at least one letter" return True, "Password is valid"
print("=== User Registration ===")
username = input("Enter username: ") email = input("Enter email: ") password = input("Enter password: ")
valid_u, msg_u = validate_username(username) valid_e, msg_e = validate_email(email) valid_p, msg_p = validate_password(password)
print(f"\nUsername: {msg_u}") print(f"Email: {msg_e}") print(f"Password: {msg_p}")
if valid_u and valid_e and valid_p: print("\nRegistration successful!") else: print("\nRegistration failed. Please fix the errors above.")
This is close to real production code — input validation is something every developer writes.
Quick Reference — All String Methods
text = " Hello World "
# Case text.upper() # HELLO WORLD text.lower() # hello world text.title() # Hello World text.capitalize() # Hello world
# Whitespace text.strip() # "Hello World" text.lstrip() # "Hello World " text.rstrip() # " Hello World"
# Search text.find("World") # index or -1 text.count("l") # count occurrences text.startswith(" H") # True/False text.endswith(" ") # True/False "Hello" in text # True/False
# Modify text.replace("World", "Python") text.split() # split into list " ".join(list) # join list into string
# Check text.isalpha() # only letters? text.isdigit() # only digits? text.isalnum() # letters and numbers? text.isspace() # only whitespace?
# Length len(text) # total characters
Exercise 🏋️
Build a Text Analyzer program:
- Ask user to enter any sentence
- Analyze and display:
Enter a sentence: Hello World this is Python programming
=== Text Analysis ===
Original text : Hello World this is Python programming
Uppercase : HELLO WORLD THIS IS PYTHON PROGRAMMING
Lowercase : hello world this is python programming
Total characters : 38
Without spaces : 32
Total words : 6
Word list : ['Hello', 'World', 'this', 'is', 'Python', 'programming']
Starts with 'H' : True
Ends with 'ing' : True
Contains 'Python': True
Count of 'o' : 3
Reversed text : gnimmargorp nohtyP si siht dlroW olleH
Hints:
- Count without spaces:
text.replace(" ", "") - Total words:
len(text.split()) - Reversed text:
text[::-1](slicing with step -1 reverses anything)