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
-
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 -
If the
split()argument is missing, the splitting standard"a b c".split()splits by space."a,b".split()does not split. -
findvsindexIffindis missing,-1andindexbecomeValueError. -
Same quotes inside quotes without escape
s = "say "hi"" # SyntaxError s = 'say "hi"' # OK s = "say \"hi\"" # OK -
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 checkexercise2.md— Email format validationexercise3.md— Text statistics (character count, word count, average length)
Next Week
Week 9. Function Basics — Code reuse