Strings & String Methods

Difficulty: Beginner

Question

Explain Python strings, common string methods, and f-string formatting.

Answer

Strings in Python are immutable sequences of Unicode characters. They can be created with single quotes, double quotes, or triple quotes for multiline.

Key characteristics: - Immutable: any operation creates a new string - Indexed and sliceable: s[0], s[1:4], s[::-1] - Rich set of built-in methods for searching, transforming, and validating - f-strings (Python 3.6+) provide the most readable string formatting

Code examples

String Methods Cheat Sheet

s = "  Hello, World!  "

# Cleaning
print(s.strip())        # 'Hello, World!'
print(s.lstrip())       # 'Hello, World!  '
print(s.rstrip())       # '  Hello, World!'

# Searching
print(s.find('World'))   # 9 (index of first match)
print(s.count('l'))      # 3
print('World' in s)      # True

# Transforming
print(s.strip().upper())        # 'HELLO, WORLD!'
print(s.strip().lower())        # 'hello, world!'
print(s.strip().title())        # 'Hello, World!'
print(s.strip().replace('World', 'Python'))  # 'Hello, Python!'

# Splitting and Joining
words = "apple,banana,cherry".split(',')
print(words)            # ['apple', 'banana', 'cherry']
print(' - '.join(words)) # 'apple - banana - cherry'

# Validation
print("hello".isalpha())   # True
print("12345".isdigit())   # True
print("hello1".isalnum())  # True

String methods always return new strings since strings are immutable. The original string is never modified.

f-strings and Formatting

name = "Alice"
age = 30
salary = 75000.5

# f-strings (Python 3.6+)
print(f"Name: {name}, Age: {age}")
print(f"Salary: ${salary:,.2f}")  # $75,000.50
print(f"{'centered':^20}")       # '      centered      '
print(f"{'left':<20}")           # 'left                '
print(f"{'right':>20}")          # '                right'

# Expressions inside f-strings
print(f"{name.upper() = }")      # "name.upper() = 'ALICE'"
print(f"{2  10 = }")           # '2  10 = 1024'

# Multiline f-strings
message = (
    f"Dear {name},\n"
    f"You are {age} years old.\n"
    f"Retirement in {65 - age} years."
)
print(message)

f-strings support format specs after a colon: alignment (<, >, ^), width, precision for floats, and comma separators.

Slicing and Reversing

s = "Python Programming"

# Slicing: s[start:stop:step]
print(s[0:6])       # 'Python'
print(s[7:])        # 'Programming'
print(s[:6])        # 'Python'
print(s[-11:])      # 'Programming'
print(s[::2])       # 'Pto rgamn'
print(s[::-1])      # 'gnimmargorP nohtyP' (reversed)

# Check palindrome
def is_palindrome(s):
    cleaned = s.lower().replace(' ', '')
    return cleaned == cleaned[::-1]

print(is_palindrome("racecar"))    # True
print(is_palindrome("A man a plan a canal Panama".replace(' ', '')))  # True

Slicing creates new strings. The [::-1] idiom is the Pythonic way to reverse a string. Negative indices count from the end.

Key points

Concepts covered

Strings, f-strings, String Methods, Slicing, Immutability