BeginnerPython Β· Lesson 9

Strings In Depth

Master Python strings: formatting, methods, slicing, and common string operations

String Basics

s1 = 'single quotes'
s2 = "double quotes"
s3 = """triple double β€” multiline"""
s4 = '''triple single β€” multiline'''
raw = r"C:\Users\name"   # no escape processing
byte = b"bytes object"

# Concatenation and repetition
print("Hello" + " " + "World")  # Hello World
print("Ha" * 3)                  # HaHaHa

f-Strings (Formatted String Literals)

name = "Alice"
age = 30
gpa = 3.857

print(f"Name: {name}")                    # Name: Alice
print(f"Age: {age}")                      # Age: 30
print(f"GPA: {gpa:.2f}")                  # GPA: 3.86
print(f"{'centered':^20}")               # 'centered' centered in 20 chars
print(f"{1000000:,}")                     # 1,000,000
print(f"{0.5:.1%}")                       # 50.0%
print(f"{42:#010b}")                      # 0b00101010 (binary)
print(f"{name!r}")                        # 'Alice' (repr)

# Expressions in f-strings:
print(f"2 + 2 = {2 + 2}")
print(f"upper: {name.upper()}")
print(f"{'Even' if age % 2 == 0 else 'Odd'}")

String Methods

s = "  Hello, World!  "

# Case
print(s.upper())          # "  HELLO, WORLD!  "
print(s.lower())          # "  hello, world!  "
print(s.title())          # "  Hello, World!  "
print(s.capitalize())     # "  hello, world!  " β†’ first char of whole string
print(s.swapcase())       # swap upper/lower

# Stripping
print(s.strip())          # "Hello, World!"
print(s.lstrip())         # "Hello, World!  "
print(s.rstrip())         # "  Hello, World!"

# Searching
print(s.find("World"))    # 9 (-1 if not found)
print(s.index("World"))   # 9 (raises ValueError if not found)
print(s.count("l"))       # 3
print("World" in s)       # True

# Checking
print("hello".isalpha())  # True
print("123".isdigit())    # True
print("abc123".isalnum()) # True
print("  ".isspace())     # True
print("Hello".startswith("He"))  # True
print("World".endswith("ld"))    # True

# Splitting and joining
csv = "a,b,c,d"
parts = csv.split(",")        # ['a', 'b', 'c', 'd']
joined = "-".join(parts)       # 'a-b-c-d'
lines = "line1\nline2\nline3".splitlines()  # ['line1', 'line2', 'line3']

# Replacing
print("foo bar foo".replace("foo", "baz"))     # baz bar baz
print("aabbcc".replace("a", "x", 1))           # xabbcc (max 1 replacement)

# Alignment
print("hello".ljust(10, "."))   # hello.....
print("hello".rjust(10, "."))   # .....hello
print("hello".center(11, "-"))  # ---hello---

# Stripping specific chars
print("***hello***".strip("*"))  # hello

String Slicing

s = "Python Programming"
#    0123456789...

print(s[0])        # P
print(s[-1])       # g
print(s[0:6])      # Python
print(s[7:])       # Programming
print(s[:6])       # Python
print(s[::2])      # Pto rgamn
print(s[::-1])     # gnimmargorP nohtyP (reversed)

String Encoding

# Encode to bytes
text = "Hello, δΈ–η•Œ"
encoded = text.encode("utf-8")
print(encoded)     # b'Hello, \xe4\xb8\x96\xe7\x95\x8c'

# Decode back
decoded = encoded.decode("utf-8")
print(decoded)     # Hello, δΈ–η•Œ

# ord() and chr()
print(ord("A"))    # 65
print(chr(65))     # A

Exercises

Exercise 1: String Reversal

Reverse a string without using [::-1] (use a loop).

Solution:

def reverse_string(s):
    result = ""
    for char in s:
        result = char + result
    return result

print(reverse_string("Python"))  # nohtyP

Exercise 2: Palindrome Check

Check if a string is a palindrome (reads the same forwards and backwards), ignoring case and spaces.

Solution:

def is_palindrome(s):
    cleaned = "".join(c.lower() for c in s if c.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome("A man a plan a canal Panama"))  # True
print(is_palindrome("hello"))                        # False

Exercise 3: Caesar Cipher

Implement a Caesar cipher that shifts letters by n positions.

Solution:

def caesar(text, shift):
    result = []
    for char in text:
        if char.isalpha():
            base = ord('A') if char.isupper() else ord('a')
            shifted = chr((ord(char) - base + shift) % 26 + base)
            result.append(shifted)
        else:
            result.append(char)
    return "".join(result)

print(caesar("Hello, World!", 3))   # Khoor, Zruog!
print(caesar("Khoor, Zruog!", -3))  # Hello, World!

Exercise 4: Count Words

Count the frequency of each word in a sentence (case-insensitive).

Solution:

sentence = "To be or not to be that is the question"
words = sentence.lower().split()
freq = {}
for word in words:
    freq[word] = freq.get(word, 0) + 1

for word, count in sorted(freq.items(), key=lambda x: -x[1]):
    print(f"{word}: {count}")