Python Topic
String Handling in Python
1. String Creation and Basics
Purpose: Represent and work with text data.
Syntax: '', "", or """ """ for multi-line strings
python
# Different ways to create strings
single_quotes = 'Hello'
double_quotes = "World"
triple_quotes = """This is a
multi-line
string"""
# Escape characters
escaped = "She said, \"Hello!\""
raw_string = r"C:\Users\Name" # Raw string - ignores escape characters
print(escaped) # She said, "Hello!"
print(raw_string) # C:\Users\Name
2. String Slicing and Indexing
Purpose: Extract portions of strings using positions.
Indexing (Accessing Single Characters):
python
text = "Python"
print(text[0]) # 'P' - first character (index 0)
print(text[-1]) # 'n' - last character
print(text[2]) # 't' - third character
Slicing (Accessing Substrings):
python
text = "Hello World"
print(text[0:5]) # "Hello" - from index 0 to 4
print(text[6:11]) # "World" - from index 6 to 10
print(text[:5]) # "Hello" - from start to index 4
print(text[6:]) # "World" - from index 6 to end
print(text[-5:]) # "World" - last 5 characters
print(text[::2]) # "HloWrd" - every second character
print(text[::-1]) # "dlroW olleH" - reversed string
Slice Syntax: [start:stop:step]
-
start: Beginning index (inclusive)
-
stop: Ending index (exclusive)
-
step: How many characters to skip
3. Common String Methods
Python strings have many built-in methods for manipulation.
Case Conversion:
python
text = "Hello Python"
print(text.upper()) # "HELLO PYTHON"
print(text.lower()) # "hello python"
print(text.title()) # "Hello Python"
print(text.capitalize()) # "Hello python"
print(text.swapcase()) # "hELLO pYTHON"
Searching and Checking:
python
text = "Hello World"
print(text.startswith("Hello")) # True
print(text.endswith("World")) # True
print(text.find("World")) # 6 (index where it starts)
print(text.find("Python")) # -1 (not found)
print(text.count("l")) # 3 (number of occurrences)
print("hello".isalpha()) # True (all alphabetic)
print("123".isdigit()) # True (all digits)
print("hello123".isalnum()) # True (alphanumeric)
Modification and Cleaning:
python
text = " Hello World "
print(text.strip()) # "Hello World" - remove whitespace
print(text.lstrip()) # "Hello World " - left strip
print(text.rstrip()) # " Hello World" - right strip
print("hello".replace("l", "L")) # "heLLo" - replace characters
# Splitting and joining
sentence = "apple,banana,cherry"
fruits = sentence.split(",") # ['apple', 'banana', 'cherry']
new_sentence = "-".join(fruits) # "apple-banana-cherry"
Alignment and Padding:
python
text = "Hello"
print(text.ljust(10, "-")) # "Hello-----" - left justify
print(text.rjust(10, "*")) # "*****Hello" - right justify
print(text.center(11, "+")) # "+++Hello+++" - center
4. String Formatting
Multiple ways to format strings with variables.
1. f-Strings (Python 3.6+ - Recommended)
python
name = "Alice"
age = 25
height = 5.7
# Basic f-string
print(f"My name is {name} and I'm {age} years old")
# Expressions inside f-strings
print(f"Next year I'll be {age + 1} years old")
# Formatting numbers
print(f"Height: {height:.2f} feet") # Height: 5.70 feet
print(f"Percentage: {0.4567:.1%}") # Percentage: 45.7%
# Alignment with f-strings
print(f"Name: {name:>10}") # Right-aligned in 10 spaces
print(f"Age: {age:<10}") # Left-aligned in 10 spaces
2. .format() Method
python
name = "Bob"
age = 30
# Positional arguments
print("My name is {} and I'm {} years old".format(name, age))
# Named arguments
print("My name is {name} and I'm {age} years old".format(name=name, age=age))
# Format specifications
print("Price: ${:.2f}".format(19.999)) # Price: $20.00
3. %-formatting (Older style)
python
name = "Charlie"
age = 35
print("My name is %s and I'm %d years old" % (name, age))
# %s = string, %d = integer, %f = float
5. Useful String Operations
Checking Content:
python
text = "Hello World"
# Membership testing
print("World" in text) # True
print("Python" not in text) # True
# Character checks
print(text.islower()) # False
print(text.isupper()) # False
print(" ".isspace()) # True (all whitespace)
Finding and Replacing:
python
text = "I love Python and Python loves me"
# Find all occurrences
index = text.find("Python")
while index != -1:
print(f"Found 'Python' at index {index}")
index = text.find("Python", index + 1)
# Replace all occurrences
new_text = text.replace("Python", "Java")
print(new_text) # "I love Java and Java loves me"
String Translation:
python
# Create a translation table
translation = str.maketrans("aeiou", "12345")
text = "hello world"
encoded = text.translate(translation)
print(encoded) # "h2ll4 w4rld"
6. Putting It All Together: Practical Examples
Example 1: Text Processing Utility
python
def process_text(text):
"""Clean and analyze text."""
# Clean the text
cleaned = text.strip().lower()
# Basic analysis
word_count = len(cleaned.split())
char_count = len(cleaned.replace(" ", ""))
sentence_count = cleaned.count('.') + cleaned.count('!') + cleaned.count('?')
# Find most common words (simplified)
words = cleaned.split()
unique_words = len(set(words))
return {
'cleaned_text': cleaned,
'word_count': word_count,
'char_count': char_count,
'sentence_count': sentence_count,
'unique_words': unique_words
}
# Test the function
sample_text = " Hello WORLD! This is a test. Hello again! "
results = process_text(sample_text)
print(f"Original: '{sample_text}'")
print(f"Cleaned: '{results['cleaned_text']}'")
print(f"Words: {results['word_count']}, Characters: {results['char_count']}")
print(f"Sentences: {results['sentence_count']}, Unique words: {results['unique_words']}")
Example 2: Password Strength Checker
python
def check_password_strength(password):
"""Check if a password meets strength requirements."""
checks = {
'length': len(password) >= 8,
'uppercase': any(char.isupper() for char in password),
'lowercase': any(char.islower() for char in password),
'digit': any(char.isdigit() for char in password),
'special': any(not char.isalnum() for char in password)
}
score = sum(checks.values())
feedback = []
if not checks['length']:
feedback.append("Password must be at least 8 characters long")
if not checks['uppercase']:
feedback.append("Add at least one uppercase letter")
if not checks['lowercase']:
feedback.append("Add at least one lowercase letter")
if not checks['digit']:
feedback.append("Add at least one number")
if not checks['special']:
feedback.append("Add at least one special character")
strength_levels = {
5: "Very Strong",
4: Strong",
3: "Medium",
2: "Weak",
1: "Very Weak"
}
strength = strength_levels.get(score, "Very Weak")
return {
'score': score,
'strength': strength,
'feedback': feedback
}
# Test passwords
passwords = ["weak", "Better123", "Strong@Pass123!"]
for pwd in passwords:
result = check_password_strength(pwd)
print(f"Password: {pwd}")
print(f"Strength: {result['strength']} (Score: {result['score']}/5)")
for feedback in result['feedback']:
print(f" {feedback}")
print()
Example 3: Data Formatting for Reports
python
def generate_report(products):
"""Generate a formatted sales report."""
if not products:
return "No products to report"
# Header
header = "SALES REPORT".center(50, "=")
# Table rows
rows = []
total_sales = 0
for product in products:
name = product['name'][:20].ljust(20) # Truncate and pad
price = f"${product['price']:>8.2f}"
quantity = f"{product['sold']:>4}"
revenue = product['price'] * product['sold']
total_sales += revenue
revenue_fmt = f"${revenue:>9.2f}"
rows.append(f"{name} {price} x{quantity} = {revenue_fmt}")
# Footer
footer = f"\nTOTAL SALES: ${total_sales:,.2f}".center(50)
return f"{header}\n" + "\n".join(rows) + f"\n{footer}"
# Sample data
products = [
{'name': 'Laptop', 'price': 999.99, 'sold': 15},
{'name': 'Mouse', 'price': 25.50, 'sold': 42},
{'name': 'Keyboard', 'price': 75.00, 'sold': 23},
{'name': 'Monitor', 'price': 299.99, 'sold': 8}
]
print(generate_report(products))
Key Takeaways:
-
f-strings are the modern, preferred way for string formatting
-
Slicing is powerful for extracting substrings:
[start:stop:step] -
String methods are your best friends for manipulation
-
Strings are immutable - methods return new strings rather than modifying in place
-
Choose the right tool for your specific string operation
Tips: Remember that strings are immutable! Every string method that "modifies" a string actually returns a new string. The original remains unchanged.
Comments (0)
No comments yet. Be the first to comment!