Python Series track

Week 08 · Basic Track

Week 8 — String Methods & Formatting

Strings are immutable sequences with a rich method library. Learn to slice, search, replace, split, join, and format text for real-world use.

Basic Track2 min readFree lesson

Level: Basic | Prerequisite: Week 7 (Data Structures)

Learning Goals

  • String Indexing and Slicing
  • Frequently Used String Methods (split, join, strip, replace, etc.)
  • Advanced f-strings (Alignment and Width)
  • Escape Characters (\n, \t)

1. String Basics

Strings are immutable. Indexing and slicing work the same as lists.

s = "Python"
print(s[0])         # P
print(s[-1])        # n
print(s[1:4])       # yth
print(len(s))       # 6

#s[0] = "X"  # TypeError — cannot be changed

2. Commonly used methods

Method Function Example
lower() / upper() Uppercase/Lowercase "Hi".upper() → "HI"
strip() Remove whitespace from both sides " hi ".strip() → "hi"
lstrip() / rstrip() Remove Left/Right whitespace
split(sep) Split into a list "a,b,c".split(",") → ["a","b","c"]
join(seq) Join a list ",".join(["a","b"]) → "a,b"
replace(old, new) Replace "foo".replace("o", "*") → "f**"
find(x) / index(x) Find position "hello".find("l") → 2
count(x) Count "hello".count("l") → 2
startswith(x) / endswith(x) Check Start/End "abc".endswith("c") → True
isdigit() / isalpha() Check Number/Letter

3. Advanced f-strings

name = "Alice"
score = 92.345

print(f"{name:<10}|")       #Left align width 10
print(f"{name:>10}|")       #Right align
print(f"{name:^10}|")       #Center
print(f"{name:*^10}|")      #Fill character * center

print(f"{score:.2f}")        #92.35  (two decimal places)
print(f"{1234567:,}")        #1,234,567  (thousands comma)
print(f"{0.85:.0%}")         # 85%
print(f"{255:b} {255:x}")    #Binary, Hexadecimal

4. Escape Characters

Notation Meaning
\n Newline
\t Tab
\\ Backslash
\" Double Quote
\' Single Quote
print("Line1
Line2")        #Two lines
print("Name	Age")      #Tab separated
print("Path: C:\\dev")    # C:\dev

#raw string: ignore escape
print(r"C:\dev\new")      # C:\dev\new

5. Converting Between Strings and Lists

csv = "Apple,Banana,Grape"
fruits = csv.split(",")             #['Apple', 'Banana', 'Grape']

joined = " | ".join(fruits)         #"Apple | Banana | Grape"

Key Examples (examples/)

File Content
01_methods.py Commonly Used Methods
02_split_join.py split / join Pattern
03_fstring_format.py Advanced f-strings
04_escape.py Escape Characters

⚠️ Common Mistakes

  1. Trying to modify the original string

    s = "hello"
    s.replace("l", "L")    #Keep 's' as it is!
    s = s.replace("l", "L")  #You need to reassign the result
    
  2. If the split() argument is missing, the splitting standard "a b c".split() splits by space. "a,b".split() does not split.

  3. find vs index If find is missing, -1 and index become ValueError.

  4. Same quotes inside quotes without escape

    s = "say "hi""    # SyntaxError
    s = 'say "hi"'    # OK
    s = "say \"hi\""  # OK
    
  5. Printing braces in f-strings

    print(f"{name}")     #Variable
    print(f"{{name}}")   #Just print {name}
    

❓ FAQ

Q1. Does string length count Korean characters as one character? A. len() counts by code points, so usually 1 character. Emojis and combined characters are exceptions.

Q2. How to compare ignoring case? A. s1.lower() == s2.lower() or s1.casefold() == s2.casefold() (more accurately).

Q3. Are there multiple ways to insert variable values into a string? A. Old method: % , .format(). Currently recommended: f-string (fastest and most readable).

📝 Exercises (exercises/)

  • exercise1.md — Palindrome check
  • exercise2.md — Email format validation
  • exercise3.md — Text statistics (character count, word count, average length)

Next Week

Week 9. Function Basics — Code reuse

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_methods.pyPython
s = "  Hello, Python!  "

print(s.strip())                   # "Hello, Python!"
print(s.lower())                   # "  hello, python!  "
print(s.upper())                   # "  HELLO, PYTHON!  "
print(s.replace("Python", "World"))
print(s.find("Python"))            # 9
print(s.count("l"))                # 3
print(s.startswith("  H"))         # True
print(s.endswith("!  "))           # True
print("123".isdigit())             # True
print("abc".isalpha())             # True
examples/02_split_join.pyPython
csv = "Apple,Banana,Grape"
fruits = csv.split(",")
print(fruits)

joined = " | ".join(fruits)
print(joined)

#Separated by spaces
s = "Hello   World    Python"
print(s.split())   # ['Hello', 'World', 'Python']

#Separated by line breaks
text = "Line 1
Line 2
Line 3"
print(text.splitlines())
examples/03_fstring_format.pyPython
name = "Alice"
score = 92.345
price = 1234567

print(f"{name:<10}|")    #Left align
print(f"{name:>10}|")    #Right align
print(f"{name:^10}|")    #Center
print(f"{name:*^10}|")   #Center, fill *

print(f"{score:.2f}")    # 92.35
print(f"{price:,}")      # 1,234,567
print(f"{0.85:.0%}")     # 85%
print(f"{255:b}")        #11111111 (binary)
print(f"{255:x}")        #ff (hexadecimal)

#Table format
data = [("Alice", 92), ("Bob", 78), ("Charlie", 100)]
for n, s in data:
    print(f"{n:<10}{s:>5} points")
examples/04_escape.pyPython
print("Line1
Line2
Line3")
print("Name	Age	Score")
print("Backslash: \")
print("Quote: "")
print('Inside single quote: '')

# raw string
print(r"C:\dev\new\test.py")

#Multiline
print("""Multiple lines
of text
are also possible""")

Assignment

Goal

Check if the input string reads the same forwards and backwards.

Requirements

  • Ignore spaces and letter case
  • If it is a palindrome, output "It is a palindrome", otherwise "It is not a palindrome"

Input/Output Example

String: Goose
It is a palindrome

String: A man a plan a canal Panama
It is a palindrome

String: hello
It is not a palindrome

Assignment 2. Email Format Validation

Goal

Simply check if an email address matches the format.

Validation Rules (Simple Version)

  • Must contain @ exactly once
  • . must appear at least once after @
  • No spaces

Input/Output Example

Email: [email protected]
Valid email

Email: foo@@bar.com
Incorrect format

Email: nobody
Incorrect format

Assignment 3. Text Statistics

Goal

Input a sentence and output the number of characters, number of words, and average word length.

Requirements

  • Character count excludes spaces
  • Word count is based on splitting by spaces
  • Average word length rounded to two decimal places

Input/Output Example

Sentence: Hello Python world

Number of characters (excluding spaces): 16
Number of words: 3
Average word length: 5.33
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
s = input("String:")
cleaned = s.replace(" ", "").lower()

if cleaned == cleaned[::-1]:
    print("It is a palindrome")
else:
    print("It is not a palindrome")
solution2.pyPython
email = input("Email:").strip()

if " " in email:
    print("Incorrect format")
elif email.count("@") != 1:
    print("Incorrect format")
else:
    local, _, domain = email.partition("@")
    if "." not in domain or not local or not domain:
        print("Incorrect format")
    else:
        print("Valid email")
solution3.pyPython
text = input("Sentence:")

char_count = len(text.replace(" ", ""))
words = text.split()
word_count = len(words)
avg_len = sum(len(w) for w in words) / word_count if word_count else 0

print(f"Number of characters (excluding spaces): {char_count}")
print(f"Number of words: {word_count}")
print(f"Average word length: {avg_len:.2f}")

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now