Python String Methods You Will Actually Use

Case conversion, whitespace trimming, searching, counting and the is-something tests, organised by the job they do rather than alphabetically.

Every method returns a new string

Strings are immutable, so no method on this page changes the original. Each one returns a new string that you must assign or use immediately.

name = "  meera  "
name.strip()                # discarded
name = name.strip()         # kept

Changing case

MethodDoes"hello WORLD" becomes
upper()Everything uppercaseHELLO WORLD
lower()Everything lowercasehello world
title()First letter of each wordHello World
capitalize()First letter only, rest lowercasedHello world
swapcase()Inverts each letterHELLO world
casefold()Aggressive lowercasing for comparisonhello world
text = "hello WORLD"
print(text.upper(), text.title(), text.capitalize(), sep=" | ")

# casefold handles cases lower() does not
print("STRASSE".lower() == "straße".lower())        # False
print("STRASSE".casefold() == "straße".casefold())  # True
title() is naive: it capitalises after every non letter, so "it's" becomes "It'S". For real headings, capitalise words yourself.

Trimming whitespace

raw = "\t  meera nair \n"

print(repr(raw.strip()))       # 'meera nair'  - both ends
print(repr(raw.lstrip()))      # 'meera nair \n' - left only
print(repr(raw.rstrip()))      # '\t  meera nair' - right only

# strip removes any of the given CHARACTERS, not a prefix string
print("xxhelloxx".strip("x"))      # hello
print("www.example.com".strip("cmowz."))   # example  <- surprising

# For a genuine prefix or suffix, use these (Python 3.9+)
print("www.example.com".removeprefix("www."))   # example.com
print("report.txt".removesuffix(".txt"))        # report

strip("cmowz.") removed every leading and trailing character that appeared in that set. That is what strip does, and it catches people out constantly. Use removeprefix and removesuffix when you mean a specific string.

Searching

text = "python programming is programming"

print(text.find("programming"))       # 7   - first index, or -1 if absent
print(text.find("java"))              # -1  - no exception
print(text.rfind("programming"))      # 21  - searching from the right

print(text.index("programming"))      # 7
# print(text.index("java"))           # ValueError

print(text.count("programming"))      # 2
print(text.count("m"))                # 4

print(text.startswith("python"))      # True
print(text.endswith(("ing", "ed")))   # True - a tuple tests several suffixes
print(text.find("gram", 20))          # search starting at index 20
FoundNot foundUse when
findindex-1Absence is normal
indexindexValueErrorAbsence is a bug
inTrueFalseYou only need to know whether

Replacing

text = "one two two three"

print(text.replace("two", "2"))        # one 2 2 three
print(text.replace("two", "2", 1))     # one 2 two three - only the first
print(text.replace(" ", ""))           # onetwotwothree

# Chained replacements read fine for a couple of cases
cleaned = text.replace(",", "").replace(".", "").strip()

The is-something tests

All of these return True or False, and all of them return False for an empty string.

MethodTrue when every character is
isdigit()A digit
isnumeric()Any numeric character, including fractions and Roman numerals
isdecimal()A plain decimal digit; the strictest of the three
isalpha()A letter
isalnum()A letter or a digit
isspace()Whitespace
islower() / isupper()Lowercase / uppercase (ignoring non letters)
istitle()Title cased
isidentifier()A legal Python name
print("12345".isdigit())        # True
print("12.5".isdigit())         # False - the dot is not a digit
print("-5".isdigit())           # False - nor is the minus sign
print("".isdigit())             # False - empty is never true
print("abc123".isalnum())       # True
print("hello world".isalpha())  # False - the space is not a letter
print("   ".isspace())          # True
isdigit() is not a number validator. It rejects "-5", "12.5" and "1e3", all of which are valid numbers. To validate a number, try the conversion inside a try block.
def is_number(text):
    try:
        float(text)
        return True
    except ValueError:
        return False


print(is_number("-12.5"), is_number("abc"))     # True False

Padding and alignment

print("7".zfill(3))              # 007
print("-7".zfill(4))             # -007  - the sign stays in front
print("left".ljust(10, "."))     # left......
print("right".rjust(10, "."))    # .....right
print("mid".center(11, "-"))     # ----mid----

for name, score in [("Meera", 92), ("Arun", 7)]:
    print(name.ljust(10), str(score).rjust(3))

A practical cleaning function

def clean_name(raw):
    """Normalise a name typed by a user."""
    name = raw.strip()
    name = " ".join(name.split())      # collapse repeated internal spaces
    return name.title()


print(clean_name("   meera    NAIR  "))     # Meera Nair

Common mistakes

  • Not assigning the result of a method.
  • Using strip("abc") expecting it to remove the literal prefix "abc".
  • Using isdigit() to validate numbers that may be negative or decimal.
  • Using index where find was meant, and getting an unhandled ValueError.
  • Trusting title() on text containing apostrophes or hyphens.
  • Comparing user input without casefold().

Best practices

  • Use in when you only need to know whether something is present.
  • Use removeprefix and removesuffix for exact affixes.
  • Normalise input once, near the point of entry: strip, collapse spaces, casefold if comparing.
  • Validate numbers by converting inside try, not by inspecting characters.

Practice

  1. Explain why "mississippi".strip("mip") returns "ss".
  2. Write a function that reports whether a string is a valid Python identifier and is not a keyword.
  3. Format a table of five names and scores so the columns line up, using only ljust and rjust.
  4. Write a validator that accepts "42", "-42" and "4.2" but rejects "4 2" and "".
  5. Count how many times each vowel appears in a sentence using count.

Conclusion

The string methods divide into five jobs: change case, trim whitespace, search, replace and test. Learn one method well from each group and look the rest up. The two that will bite you are strip, which takes a character set rather than a prefix, and isdigit, which is not a number check.

Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All Python notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.