Part of Python for Beginners

Python Tutorial for Beginners #3 - String Operations (Methods, Slicing, f-strings)

Sandy LaneSandy Lane

Video: Python Tutorial for Beginners #3 - String Operations (Methods, Slicing, f-strings) by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Python String Operations

.upper(), .lower(), .strip(), .split(), .join() — the workhorse methods. s[1:4] for slicing. f"hello {name}" for f-strings — the modern format syntax.

Strings are Python's most-used data type. Understanding their methods, slicing, and formatting unlocks ~half of everyday Python code.

String methods

text = "  Python Programming  "
print(text.upper())     # '  PYTHON PROGRAMMING  '
print(text.lower())     # '  python programming  '
print(text.title())     # '  Python Programming  '
print(text.strip())     # 'Python Programming' (no whitespace)

Methods are called with dot notation. They return new strings — strings are immutable, so the original is unchanged.

print(text)             # still '  Python Programming  '
clean = text.strip()    # assign to keep the result

Common case methods: .upper(), .lower(), .title(), .capitalize(), .swapcase().

Whitespace methods: .strip(), .lstrip(), .rstrip() (left/right).

Split and join

words = "apple,banana,cherry"
fruit_list = words.split(",")
print(fruit_list)   # ['apple', 'banana', 'cherry']

rejoined = " - ".join(fruit_list)
print(rejoined)     # 'apple - banana - cherry'

split(delim) cuts a string into a list at every delim. join(iterable) connects them back with delim between each.

These two are the bread and butter of text processing. Parse CSV, format lists, transform.

For whitespace splitting (any whitespace, multiple spaces collapsed):

"hello   world\tfoo".split()
# ['hello', 'world', 'foo']

split() (no arg) is special — splits on runs of whitespace.

Indexing and slicing

word = "Python"

word[0]    # 'P' — first char (zero-indexed)
word[2]    # 't' — third char
word[-1]   # 'n' — last char (negative = from end)
word[-2]   # 'o' — second to last

Strings are sequences of characters. Index with [i], 0-based. Negative indices count from the end (-1 is last).

Slicing extracts a range:

word[0:3]    # 'Pyt'  — chars 0, 1, 2 (3 is exclusive)
word[2:]     # 'thon' — from index 2 to end
word[:4]     # 'Pyth' — start to index 4 (exclusive)
word[::2]    # 'Pto'  — every 2nd char
word[::-1]   # 'nohtyP' — reversed

[start:end:step]. Any of the three can be omitted; defaults are 0, len, 1.

Slicing returns a new string. The original isn't modified.

f-strings (the modern way)

name = "Alice"
age = 25
print(f"{name} is {age} years old")
# 'Alice is 25 years old'

f"..." strings interpolate values via {expression}. Anything in {} is evaluated and converted to string.

x = 3.14159
print(f"{x:.2f}")        # '3.14' — 2 decimal places
print(f"{42:>10}")        # '        42' — right-aligned, width 10
print(f"{42:0>5}")        # '00042' — zero-padded
print(f"{1234567:,}")     # '1,234,567' — thousands separator
print(f"{0.1234:.0%}")    # '12%' — percentage

Format specifiers after : — same syntax as str.format() and printf flavors.

f-strings are the canonical formatting style in modern Python (3.6+).

Older formatting styles (avoid for new code)

name = "Alice"
age = 25

# Old % formatting (C-style) — Python 1.x onwards
print("%s is %d" % (name, age))

# .format() method — Python 2.6+
print("{} is {}".format(name, age))
print("{0} is {1}".format(name, age))   # positional
print("{name} is {age}".format(name=name, age=age))   # named

# f-strings — Python 3.6+ (preferred)
print(f"{name} is {age}")

You'll see all three in real codebases. f-strings are the cleanest; use them for new code.

Other common methods

"hello".startswith("he")    # True
"hello".endswith("lo")      # True
"hello".replace("l", "L")   # 'heLLo'
"hello".count("l")          # 2
"hello".find("l")           # 2 (first index, or -1)
"hello".index("l")          # 2 (or raises ValueError)
"hello, world".isalpha()    # False (comma + space)
"hello".isdigit()           # False
"123".isdigit()             # True

The full list is at dir(str). Most names are self-explanatory.

String concatenation

greeting = "Hello"
name = "Alice"
result = greeting + ", " + name + "!"
print(result)   # 'Hello, Alice!'

# f-string is cleaner:
result = f"{greeting}, {name}!"

+ concatenates strings. Works but reads awkwardly for many parts.

For many concatenations, use .join() (not += in a loop — that's O(n²)):

parts = []
for word in many_words:
    parts.append(word)
result = " ".join(parts)   # one allocation

Multi-line strings

text = """
This is
a multi-line
string.
"""

Triple quotes preserve newlines. Useful for SQL queries, docstrings, embedded text.

For Python source code embedded in tests (e.g., dedent):

import textwrap
text = textwrap.dedent("""
    indented
    text
""")

dedent strips the common leading whitespace.

Encoding and bytes

s = "Hello, 世界"
b = s.encode("utf-8")
print(b)                 # b'Hello, \xe4\xb8\x96\xe7\x95\x8c'
print(b.decode("utf-8"))  # 'Hello, 世界'

Python strings are sequences of Unicode code points. To send/receive bytes (files, network), encode/decode.

UTF-8 is the de facto default. Use it unless you have a specific reason not to.

Common stumbles

Modifying a string. s[0] = "H" errors — strings are immutable. Build a new one: "H" + s[1:].

int("3.14"). Errors — int parses ints only. Use float("3.14") first.

split without arg vs with " ". split() collapses whitespace runs; split(" ") doesn't.

Forgetting f-string prefix. "{x}" is just text. f"{x}" interpolates.

Mixing + with non-strings. "x = " + 5 errors. Use f-string: f"x = {5}".

s.replace("a", "b") not modifying. It returns a new string. Assign: s = s.replace(...).

What's next

Lesson 4: numbers and math. All seven arithmetic operators, the math module, built-in numeric functions.

Recap

String methods return new strings (strings are immutable). Indexing: s[0] first, s[-1] last. Slicing: s[start:end:step] returns a substring. f-strings: f"{expression}" interpolates values; format specifiers after :. Common operations: .upper(), .lower(), .strip(), .split(), .join(), .replace(), .startswith(), .endswith(). Use .join() for many concatenations (not +=).

Next lesson: numbers and math.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.