Python · Syntax · Beginner

String Methods & f-strings

10 tasks

Learn the most important built-in string methods and how to format strings using f-strings.

String Methods

#
Strings in Python are immutable sequences of characters. Every string method returns a **new** string — the original is never modified. ## Case transformation ```python text = "hello world" print(text.upper()) # "HELLO WORLD" print(text.lower()) # "hello world" print(text.capitalize()) # "Hello world" print(text.title()) # "Hello World" print(text.swapcase()) # "HELLO WORLD" ``` ## Removing whitespace ```python s = " hello " print(s.strip()) # "hello" — both sides print(s.lstrip()) # "hello " — left only print(s.rstrip()) # " hello" — right only ``` `strip()` is extremely common for cleaning user input. ## Search and check ```python s = "Python is great" print(s.find("is")) # 7 — index of first match, -1 if not found print(s.index("is")) # 7 — same, but raises ValueError if not found print(s.count("t")) # 2 print(s.startswith("Py")) # True print(s.endswith("eat")) # True print("123".isdigit()) # True print("abc".isalpha()) # True print("abc123".isalnum()) # True ``` ## Replacing and splitting ```python s = "one two three" print(s.replace("two", "2")) # "one 2 three" print(s.split()) # ["one", "two", "three"] print(s.split(" ", maxsplit=1)) # ["one", "two three"] ``` `split()` without arguments splits on any whitespace and removes empty strings. ## Joining ```python words = ["one", "two", "three"] print(", ".join(words)) # "one, two, three" print("-".join(words)) # "one-two-three" print("".join(words)) # "onetwothree" ``` `join` is the opposite of `split` — always call it on the **separator**, not the list. ## Padding and alignment ```python s = "hello" print(s.ljust(10)) # "hello " print(s.rjust(10)) # " hello" print(s.center(11, "-")) # "---hello---" print("42".zfill(5)) # "00042" ``` ## Key rule Since strings are immutable, you must **assign** the result: ```python name = " Alice " name = name.strip() # correct name.strip() # does nothing — result is discarded ```

f-strings

#
f-strings (formatted string literals) are the modern, readable way to embed values and expressions directly in strings. They are faster than `%` formatting and `.format()`. ## Basic syntax ```python name = "Alice" age = 30 print(f"Hello, {name}! You are {age} years old.") # Hello, Alice! You are 30 years old. ``` Any variable or expression goes inside `{}`: ```python a, b = 7, 3 print(f"{a} + {b} = {a + b}") # 7 + 3 = 10 print(f"{'hello'.upper()}") # HELLO ``` ## Number formatting ```python price = 9.5 pi = 3.14159 score = 0.876 print(f"{price:.2f}") # 9.50 — 2 decimal places print(f"{pi:.4f}") # 3.1416 — 4 decimal places print(f"{score:.1%}") # 87.6% — percentage print(f"{1000000:,}") # 1,000,000 — thousands separator print(f"{42:08d}") # 00000042 — zero-padded integer print(f"{42:>10}") # 42 — right-aligned in width 10 print(f"{42:<10}") # 42 — left-aligned print(f"{42:^10}") # 42 — centered ``` ## Debugging with `=` ```python x = 42 items = [1, 2, 3] print(f"{x=}") # x=42 print(f"{items=}") # items=[1, 2, 3] print(f"{len(items)=}") # len(items)=3 ``` The `=` specifier prints both the expression and its value — perfect for quick debugging. ## Multiline f-strings ```python name = "Bob" total = 123.45 message = ( f"Order summary\n" f"Customer: {name}\n" f"Total: ${total:.2f}" ) print(message) # Order summary # Customer: Bob # Total: $123.45 ``` ## Practical example ```python def format_report(name, score, passed): status = "PASS" if passed else "FAIL" return f"[{status}] {name}: {score:.1f}/100" print(format_report("Alice", 87.5, True)) # [PASS] Alice: 87.5/100 print(format_report("Bob", 45.0, False)) # [FAIL] Bob: 45.0/100 ```

String Methods & f-strings Reference

#
## String methods | Method | What it does | Example | |---|---|---| | `s.upper()` | ALL CAPS | `"hi".upper()` → `"HI"` | | `s.lower()` | all lowercase | `"HI".lower()` → `"hi"` | | `s.capitalize()` | First letter capital | `"hi".capitalize()` → `"Hi"` | | `s.title()` | Title Case | `"hi there".title()` → `"Hi There"` | | `s.strip()` | Remove whitespace both sides | `" hi ".strip()` → `"hi"` | | `s.lstrip()` / `s.rstrip()` | Remove left / right | — | | `s.replace(old, new)` | Replace all occurrences | `"aXa".replace("X","b")` → `"aba"` | | `s.split(sep)` | Split into list | `"a,b".split(",")` → `["a","b"]` | | `sep.join(lst)` | Join list into string | `",".join(["a","b"])` → `"a,b"` | | `s.find(sub)` | Index of first match (-1 if none) | `"abc".find("b")` → `1` | | `s.index(sub)` | Index (raises ValueError) | — | | `s.count(sub)` | Count occurrences | `"aaa".count("a")` → `3` | | `s.startswith(p)` | Starts with prefix | `"abc".startswith("ab")` → `True` | | `s.endswith(p)` | Ends with suffix | `"abc".endswith("bc")` → `True` | | `s.isdigit()` | All digits | `"123".isdigit()` → `True` | | `s.isalpha()` | All letters | `"abc".isalpha()` → `True` | | `s.isalnum()` | Letters and digits | — | | `s.ljust(n)` | Left-align in width n | — | | `s.rjust(n)` | Right-align in width n | — | | `s.center(n, c)` | Center in width n, fill c | — | | `s.zfill(n)` | Zero-pad to width n | `"7".zfill(3)` → `"007"` | ## f-string format specifiers | Specifier | Meaning | Example | |---|---|---| | `:.2f` | Float, 2 decimal places | `f"{3.1:.2f}"` → `"3.10"` | | `:.1%` | Percentage, 1 decimal | `f"{0.875:.1%}"` → `"87.5%"` | | `:,` | Thousands separator | `f"{1000:,}"` → `"1,000"` | | `:05d` | Zero-padded integer | `f"{7:05d}"` → `"00007"` | | `:>10` | Right-align in width 10 | `f"{'x':>10}"` → `" x"` | | `:<10` | Left-align | `f"{'x':<10}"` → `"x "` | | `:^10` | Center | `f"{'x':^10}"` → `" x "` | | `=` | Debug: show name=value | `f"{x=}"` → `"x=42"` | ## Common patterns ```python # Clean user input clean = user_input.strip().lower() # Check and transform if s.startswith("http"): s = s[len("http"):] # Build sentence from list sentence = " ".join(words) + "." # Format table row row = f"{name:<20} {score:>6.1f} {'PASS' if score >= 60 else 'FAIL'}" ```
01

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
02

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
03

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
04

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 *****
05

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
06

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
07

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.
08

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
09

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
10

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%