Python · Syntax · Beginner
String Methods & f-strings
Learn the most important built-in string methods and how to format strings using f-strings.
Quick topic start and explanations before exercises (exercises below):
f-strings
#String Methods & f-strings Reference
#Exercises:
Title Case Name
#Write a function `format_name(name)` that takes a string and returns it in title case (every word starts with a capital letter). Example: `format_name("john doe")` → `"John Doe"`.
def format_name(name):
pass
print(format_name("john doe")) # John Doe
print(format_name("ALICE SMITH")) # Alice Smith
Solution
def format_name(name):
return name.title()
print(format_name("john doe")) # John Doe
print(format_name("ALICE SMITH")) # Alice Smith
Clean Input
#Write a function `clean(s)` that removes leading/trailing whitespace and converts the string to lowercase. Example: `clean(" Hello World ")` → `"hello world"`.
def clean(s):
pass
print(clean(" Hello World ")) # hello world
print(clean(" Python ")) # python
Solution
def clean(s):
return s.strip().lower()
print(clean(" Hello World ")) # hello world
print(clean(" Python ")) # python
Count Word
#Write a function `count_word(text, word)` that counts how many times `word` appears in `text` (case-insensitive). Example: `count_word("Apple apple APPLE", "apple")` → `3`.
def count_word(text, word):
pass
print(count_word("Apple apple APPLE", "apple")) # 3
print(count_word("cat cat dog cat", "cat")) # 3
Solution
def count_word(text, word):
return text.lower().count(word.lower())
print(count_word("Apple apple APPLE", "apple")) # 3
print(count_word("cat cat dog cat", "cat")) # 3
Censor Word
#Write a function `censor(text, word)` that replaces all occurrences of `word` in `text` with asterisks of the same length. Example: `censor("I love cats", "cats")` → `"I love ****"`.
def censor(text, word):
pass
print(censor("I love cats", "cats")) # I love ****
print(censor("hello world", "world")) # hello *****
Solution
def censor(text, word):
return text.replace(word, "*" * len(word))
print(censor("I love cats", "cats")) # I love ****
print(censor("hello world", "world")) # hello *****
Join with Dash
#Write a function `dashify(s)` that splits the string into words and joins them with a dash. Example: `dashify("hello world foo")` → `"hello-world-foo"`.
def dashify(s):
pass
print(dashify("hello world foo")) # hello-world-foo
print(dashify("one two three")) # one-two-three
Solution
def dashify(s):
return "-".join(s.split())
print(dashify("hello world foo")) # hello-world-foo
print(dashify("one two three")) # one-two-three
Check URL
#Write a function `is_url(s)` that returns `True` if the string starts with `"http://"` or `"https://"` and ends with a domain extension like `".com"`, `".org"`, or `".net"`. Otherwise return `False`.
def is_url(s):
pass
print(is_url("https://example.com")) # True
print(is_url("http://site.org")) # True
print(is_url("ftp://bad.com")) # False
print(is_url("https://no-ext.xyz")) # False
Solution
def is_url(s):
starts_ok = s.startswith("http://") or s.startswith("https://")
ends_ok = s.endswith(".com") or s.endswith(".org") or s.endswith(".net")
return starts_ok and ends_ok
# Shorter version using tuples:
def is_url_v2(s):
return s.startswith(("http://", "https://")) and s.endswith((".com", ".org", ".net"))
print(is_url("https://example.com")) # True
print(is_url("ftp://bad.com")) # False
Greeting f-string
#Write a function `greet(name, age)` that returns a greeting using an f-string: `"Hello, {name}! You are {age} years old."`. Example: `greet("Alice", 25)` → `"Hello, Alice! You are 25 years old."`.
def greet(name, age):
pass
print(greet("Alice", 25)) # Hello, Alice! You are 25 years old.
print(greet("Bob", 30)) # Hello, Bob! You are 30 years old.
Solution
def greet(name, age):
return f"Hello, {name}! You are {age} years old."
print(greet("Alice", 25)) # Hello, Alice! You are 25 years old.
print(greet("Bob", 30)) # Hello, Bob! You are 30 years old.
Format Price
#Write a function `format_price(amount)` that formats a number as a price with 2 decimal places and a `$` prefix. Example: `format_price(9.5)` → `"$9.50"`, `format_price(1000)` → `"$1,000.00"`.
def format_price(amount):
pass
print(format_price(9.5)) # $9.50
print(format_price(1000)) # $1,000.00
print(format_price(0.99)) # $0.99
Solution
def format_price(amount):
return f"${amount:,.2f}"
print(format_price(9.5)) # $9.50
print(format_price(1000)) # $1,000.00
print(format_price(0.99)) # $0.99
Safe Find
#Write a function `safe_find(text, sub)` that returns the index of the first occurrence of `sub` in `text`, or `-1` if not found. Do NOT use `.index()` (it raises an error). Example: `safe_find("hello", "ll")` → `2`, `safe_find("hello", "x")` → `-1`.
def safe_find(text, sub):
pass
print(safe_find("hello", "ll")) # 2
print(safe_find("hello", "x")) # -1
print(safe_find("python", "on")) # 4
Solution
def safe_find(text, sub):
return text.find(sub)
print(safe_find("hello", "ll")) # 2
print(safe_find("hello", "x")) # -1
print(safe_find("python", "on")) # 4
Progress Bar
#Write a function `progress_bar(done, total, width=20)` that returns a text progress bar. Fill with `"#"` for completed portion, `"."` for remaining. Example: `progress_bar(3, 10, 10)` → `"[###.......] 30%"`.
def progress_bar(done, total, width=20):
pass
print(progress_bar(3, 10, 10)) # [###.......] 30%
print(progress_bar(0, 10, 10)) # [..........] 0%
print(progress_bar(10, 10, 10)) # [##########] 100%
Solution
def progress_bar(done, total, width=20):
filled = int(width * done / total)
bar = "#" * filled + "." * (width - filled)
percent = done / total
return f"[{bar}]{percent:>5.0%}"
print(progress_bar(3, 10, 10)) # [###.......] 30%
print(progress_bar(0, 10, 10)) # [..........] 0%
print(progress_bar(10, 10, 10)) # [##########] 100%