String methods

Topic 1 of 2 in Working with text6 min readBeginnerFree course

Overview

Text arrives messy: extra spaces, random capitals, values separated by commas, lines that need checking. Python’s str type has dozens of methods that handle these jobs in a single call. This lesson covers the ones you’ll use every week.

Useful string methods, with s = “  Hello, World  “. s.strip() gives “Hello, World”. s.lower() and s.upper() change case: “  hello, world  “. s.strip().split(”, “) gives [“Hello”, “World”]. “-”.join([“a”, “b”, “c”]) gives “a-b-c”. s.replace(“World”, “Py”) gives “  Hello, Py  “. s.strip().startswith(“He”) is True. “World” in s is True. s.find(“o”) gives 6, or -1 if not found. s.count(“l”) gives 3. Strings are immutable: methods return NEW strings. Write s = s.strip() to keep the result.

Remember: methods return new strings

Strings can’t change (Strings), so every method gives you a new string:

Python
name = "  asha  "
name.strip()          # returns 'asha' — but name is unchanged
name = name.strip()   # keep the result

Cleaning and changing case

Python
"  hi  ".strip()          # 'hi'      both ends
"  hi  ".lstrip()         # 'hi  '    left only
"  hi  ".rstrip()         # '  hi'    right only — great for line endings
"xxhixx".strip("x")       # 'hi'      strip specific characters

"Hello".lower()           # 'hello'
"Hello".upper()           # 'HELLO'
"ada lovelace".title()    # 'Ada Lovelace'
"hello world".capitalize()  # 'Hello world'
"Hello".swapcase()        # 'hELLO'
"Straße".casefold()       # 'strasse' — stronger lower() for comparing text

For case-insensitive comparison, compare normalised versions: a.lower() == b.lower() (or casefold() for international text).

removeprefix and removesuffix remove an exact piece from one end — unlike strip, which removes any of the given characters:

Python
"report.csv".removesuffix(".csv")   # 'report'
"Mr Smith".removeprefix("Mr ")      # 'Smith'

Searching

Python
s = "Hello, World"
"World" in s              # True
s.startswith("Hell")      # True
s.endswith((".com", ".org"))   # a tuple checks several options at once
s.find("o")               # 4 — first position, or -1 if not found
s.find("z")               # -1
s.index("z")              # ValueError — like find but raises an error
s.count("l")              # 3
s.rfind("o")              # 8 — search from the right

Replacing

Python
"I like tea".replace("tea", "coffee")      # 'I like coffee'
"a-b-c".replace("-", "")                   # 'abc'
"aaa".replace("a", "b", 2)                 # 'bba' — at most 2 replacements

Splitting and joining

These two are partners, and probably the most useful methods of all.

split breaks a string into a list:

Python
"the quick  brown fox".split()       # ['the', 'quick', 'brown', 'fox']
"tea,coffee,,cake".split(",")        # ['tea', 'coffee', '', 'cake']
"2026-12-04".split("-")              # ['2026', '12', '04']
"a=1=2".split("=", 1)                # ['a', '1=2'] — split at most once
"line one\nline two".splitlines()    # ['line one', 'line two']

With no argument, split() splits on any run of whitespace and ignores spaces at the ends. With an argument, it splits on exactly that text, so empty items can appear.

join glues a list of strings together, with the string you call it on between the items:

Python
", ".join(["tea", "coffee", "cake"])   # 'tea, coffee, cake'
"".join(["a", "b", "c"])               # 'abc'
"\n".join(lines)                       # one item per line

join only accepts strings: ", ".join([1, 2]) is a TypeError. Convert first: ", ".join(str(n) for n in numbers).

A neat trick combining both — squash repeated spaces:

Python
" ".join("too    many   spaces".split())   # 'too many spaces'

Testing characters

These return True or False for the whole string (and False for an empty string):

Method True when every character is…
isdigit() a digit (0–9)
isalpha() a letter
isalnum() a letter or digit
isspace() whitespace
isupper() / islower() upper / lower case (ignoring non-letters)
Python
"2026".isdigit()       # True
"12.5".isdigit()       # False — the dot isn't a digit
"Asha".isalpha()       # True
"R2D2".isalnum()       # True

Padding

Python
"7".zfill(3)           # '007'
"tea".center(9, "*")   # '***tea***'
"tea".ljust(6) + "|"   # 'tea   |'

For aligning output, f-string format specifiers (next lesson) are usually neater.

Chaining

Because each method returns a string, you can chain them:

Python
email = "  Asha.Rao@Example.COM ".strip().lower()
slug = title.lower().replace(" ", "-")

Keep chains short enough to read; split long ones over several lines with intermediate variables.

Cheat sheet: clean with strip/lower, test with in/startswith, change with replace, and take apart and put together with split and join.

Exercise

Clean up a contact list

Each line of the raw text is a messy name ; email ; city record. For each non-blank line: split it on ;, strip spaces from each part, title-case the name, lower-case the email, and upper-case the city. Skip (and count) records whose email doesn’t contain exactly one @ or doesn’t end with .com or .org. Print each clean record as Name <email> (CITY), then the number skipped. Finally, make a URL slug from the title " Python Basics: Strings & Text! " → python-basics-strings-text (lower case; keep only letters, digits and spaces; then join the words with hyphens).

Python
raw = """
  asha RAO ;  Asha.Rao@Example.com ; pune
ben   jones; ben@@mail.org ; leeds

 chen li ; CHEN@uni.org;  Beijing
dee ; dee@site.net ; lagos
"""

# Clean the records

# Make the slug
title = "  Python Basics: Strings & Text!  "

Summary

  • Methods return new strings — assign the result (s = s.strip()) to keep it.
  • strip, lower, upper, title and replace clean and normalise text.
  • split() breaks text into a list (on whitespace by default); "sep".join(list) glues a list back together.
  • in, startswith, endswith, find and count search text; startswith and endswith accept a tuple of options.
  • isdigit, isalpha, isalnum, isspace and friends test what kind of characters a string contains.