Understanding and Manipulating Strings

Strings in Python are immutable sequences of Unicode characters. Immutable means every string method returns a new string rather than modifying the original; this simplifies reasoning about shared state but requires attention when building long strings in a loop (prefer ''.join(parts) to repeated +=, which quietly allocates a new string on every iteration).

Python strings support indexing and slicing like any sequence (s[0], s[-3:]) and offer a rich set of methods: .strip()/.lstrip()/.rstrip() trim whitespace, .lower()/.upper()/.title() change case, .split()/.rsplit()/.splitlines() break a string into pieces, .join() glues pieces back together, and .replace(old, new) substitutes substrings. Predicate methods like .startswith(), .endswith(), .isdigit(), and .isalpha() return booleans for quick classification.

Formatting has three modern options. The recommended one is the f-string: f'{name} scored {score:.2f}'. The str.format() method is older but equivalent. The percent operator ('%s' %% value) is legacy and should be avoided in new code; it is kept only for compatibility with very old scripts.

For anything beyond simple substitutions, use the re module for regular expressions (searching, extracting, replacing by pattern) or string.Template for user-editable templates. Remember that strings are Unicode by default in Python 3 — if you receive bytes from a file, network socket, or subprocess, decode them with bytes.decode('utf-8') before applying string methods. That one habit prevents most Unicode surprises you will meet in Understanding and Manipulating Strings.

String handling tools used in Understanding and Manipulating Strings. Skim the table before reading the code example, and click any name to open the official documentation.

ToolPurpose
.strip() / .lstrip() / .rstrip()
method
Remove whitespace or chosen characters.
.lower() / .upper() / .title()
method
Change the case of text.
.split() / .join()
method
Break a string into parts, or glue parts back together.
.replace(old, new)
method
Substitute text inside a string.
.startswith() / .endswith()
method
Check prefixes and suffixes.
f-string
syntax
Inline formatting: f"Hello, {name}".
str.format()
method
Template-style formatting with placeholders.
re module
stdlib
Regular expressions for pattern matching.

Understanding and Manipulating Strings Code example

Normalize and analyze text values for Understanding and Manipulating Strings.

# Lesson: Understanding and Manipulating Strings
# Goal: take a noisy input string, clean it, derive a slug, and count words.
# The extra lines show how the result is typically used (logging, storing, etc.).
import re


def clean_text(text: str) -> str:
    '''Collapse whitespace and strip leading/trailing spaces.'''
    return re.sub(r"\s+", " ", text).strip()


# --- main script ---------------------------------------------------------
raw = "  understanding and manipulating strings  "
clean = clean_text(raw).title()
slug = clean.lower().replace(" ", "-")
word_count = len(clean.split())

print(clean)
print(slug)
print("words:", word_count)

# follow-up use: use the cleaned values to build a filename-safe record
record = {"title": clean, "slug": slug, "words": word_count}
print("record:", record)

Walk through each part before moving to the next lesson:

1) The example defines one clear unit of logic.
2) Inputs are explicit, so behavior is reproducible.
3) Output lines are designed for quick validation.
4) The self-test section confirms expected behavior.

Try both examples below to strengthen understanding.

# Example A: defensive input cleanup
user_text_understanding_and_manipulating_strings = "  Understanding and Manipulating Strings  "
print(user_text_understanding_and_manipulating_strings.strip().upper())

# Example B: dictionary-driven lookup
levels_understanding_and_manipulating_strings = {"easy": 1, "medium": 2, "hard": 3, "understanding_and_manipulating_strings": 38}
print(levels_understanding_and_manipulating_strings.get("medium", 0))
print(levels_understanding_and_manipulating_strings.get("understanding_and_manipulating_strings"))

Run these assertions after the example. If nothing prints, tests passed.

assert clean
assert "-" in slug
assert word_count >= 1

Your exact values can vary slightly (especially dates/times), but the structure should match.

Understanding And Manipulating Strings
understanding-and-manipulating-strings
words: 4