String Operations and Formatting
Master string manipulation and formatting in Python.
String Concatenation
Combine strings using +:
first = "Hello" second = "World" result = first + " " + second print(result) # Output: Hello World # Multiple concatenations greeting = "Good" + " " + "morning" + "!" print(greeting) # Output: Good morning!
String Repetition
laugh = "Ha" * 3 print(laugh) # Output: HaHaHa # Create separators separator = "=" * 50 print(separator)
String Indexing and Slicing
Access characters and substrings:
text = "Python" # Positive indexing print(text[0]) # P print(text[5]) # n # Negative indexing print(text[-1]) # n (last character) print(text[-2]) # h # Slicing [start:end:step] print(text[0:3]) # Pyt print(text[2:]) # thon print(text[:4]) # Pyth print(text[::2]) # Pto (every 2nd char) print(text[::-1]) # nohtyP (reverse)
String Methods
Python provides many built-in string methods:
Case Conversion
text = "Hello, World!" print(text.upper()) # HELLO, WORLD! print(text.lower()) # hello, world! print(text.title()) # Hello, World! print(text.capitalize()) # Hello, world! print(text.swapcase()) # hELLO, wORLD!
Searching and Checking
text = "Python Programming" # Find substring print(text.find("Pro")) # 7 print(text.find("Java")) # -1 (not found) # Count occurrences print(text.count("o")) # 2 # Check start/end print(text.startswith("Py")) # True print(text.endswith("ing")) # True # Check content print("123".isdigit()) # True print("abc".isalpha()) # True print("abc123".isalnum()) # True
Trimming and Splitting
# Remove whitespace text = " Hello " print(text.strip()) # "Hello" print(text.lstrip()) # "Hello " print(text.rstrip()) # " Hello" # Split into list sentence = "Python is awesome" words = sentence.split() print(words) # ['Python', 'is', 'awesome'] # Split by delimiter data = "apple,banana,orange" fruits = data.split(",") print(fruits) # ['apple', 'banana', 'orange'] # Join list into string words = ['Hello', 'World'] result = " ".join(words) print(result) # "Hello World"
Replacing
text = "I love Java" new_text = text.replace("Java", "Python") print(new_text) # "I love Python" # Replace multiple occurrences text = "ha ha ha" new_text = text.replace("ha", "HO") print(new_text) # "HO HO HO"
String Formatting
F-Strings (Recommended)
name = "Alice" age = 25 height = 5.6 # Basic f-string print(f"My name is {name}") # Multiple variables print(f"{name} is {age} years old") # Expressions print(f"Next year, {name} will be {age + 1}") # Formatting numbers pi = 3.14159 print(f"Pi is approximately {pi:.2f}") # 3.14 price = 19.5 print(f"Price: ${price:.2f}") # Price: $19.50
format() Method
name = "Bob" age = 30 # Positional arguments print("My name is {} and I am {}".format(name, age)) # Named arguments print("My name is {n} and I am {a}".format(n=name, a=age)) # Formatting print("Pi: {:.3f}".format(3.14159)) # Pi: 3.142 # Currency formatting print("Price: ${:.2f}".format(19.99)) # Price: $19.99
% Formatting (Old Style)
name = "Charlie" age = 35 print("My name is %s and I am %d" % (name, age)) print("Price: $%.2f" % 19.99)
Escape Characters
Special characters in strings:
# Newline print("Line 1\nLine 2") # Tab print("Column1\tColumn2") # Backslash print("C:\\Users\\Documents") # Quotes print("She said, \"Hello!\"") print('It\'s a beautiful day') # Raw strings (ignore escapes) print(r"C:\Users\Documents") # C:\Users\Documents
Practical Examples
Example 1: Format User Information
first_name = "John" last_name = "Doe" age = 28 email = "john.doe@email.com" print("=" * 40) print(f"Name: {first_name} {last_name}") print(f"Age: {age}") print(f"Email: {email}") print("=" * 40)
Example 2: Create a Receipt
item1 = "Coffee" price1 = 4.50 item2 = "Sandwich" price2 = 7.25 total = price1 + price2 print("RECEIPT") print("-" * 30) print(f"{item1:<20} ${price1:>6.2f}") print(f"{item2:<20} ${price2:>6.2f}") print("-" * 30) print(f"{'TOTAL':<20} ${total:>6.2f}")
Example 3: Username Generator
first_name = "Alice" last_name = "Smith" year = 2025 # Create username username = (first_name[:3] + last_name[:3] + str(year)[-2:]).lower() print(f"Generated username: {username}") # alismi25
Common String Operations Summary
| Method | Description | Example |
|---|---|---|
.upper() | Convert to uppercase | "hello".upper() → "HELLO" |
.lower() | Convert to lowercase | "HELLO".lower() → "hello" |
.strip() | Remove whitespace | " hi ".strip() → "hi" |
.split() | Split into list | "a b c".split() → ['a','b','c'] |
.replace() | Replace substring | "hi".replace("i","o") → "ho" |
.find() | Find substring | "hello".find("ll") → 2 |
.count() | Count occurrences | "aaa".count("a") → 3 |
Practice Exercises
- Create a program that formats personal information nicely
- Build a string that reverses the order of words in a sentence
- Extract domain from email addresses
- Create formatted receipts or invoices
- Practice all string methods with different examples
Module Complete! Move on to Module 2: Control Flow & Logic