Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 149 ยท Data Types

String Methods

Master Python's most useful string methods - changing case, strip, split and join, find and replace, startswith, count and the is-checks - with live examples.

Strings come with dozens of built-in methods: functions attached to every string that you call with a dot, like name.upper(). They handle the jobs you'll do with text constantly: cleaning up user input, breaking a line into fields, searching for words, and checking whether text looks like a number.

This lesson groups the most useful methods by job. Keep one rule from Strings in mind throughout: strings are immutable, so every method returns a new string (or another value) and leaves the original unchanged. If you want to keep the result, assign it.

Changing case

Python Case methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how .title() produces Hitchhiker'S: it capitalizes any letter that follows a non-letter, including an apostrophe. It's fine for simple labels but not for real titles or names.

For case-insensitive comparisons, use .casefold(). It's like .lower() but more thorough with some languages, such as turning the German รŸ into ss:

Python
print("STRASSE".casefold() == "straรŸe".casefold())   # True
print("STRASSE".lower() == "straรŸe".lower())         # False

Trimming whitespace and characters

Text from users and files often has stray spaces, tabs or newlines at the ends. .strip() removes them from both ends; .lstrip() and .rstrip() work on one side only:

Python strip, lstrip, rstrip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

repr() shows the quotes so you can see exactly where the spaces went. The last line is a common trap: .strip("w.moc") removes any of the characters w, ., m, o and c from both ends, not the text ".com". To remove an exact piece of text from one end, use .removeprefix() and .removesuffix():

Python
print("www.example.com".removeprefix("www."))   # example.com
print("report.csv".removesuffix(".csv"))         # report
print("report.csv".removesuffix(".txt"))         # report.csv (no match, unchanged)

Splitting and joining

.split() breaks a string into a list of pieces. With no argument, it splits on any run of whitespace and ignores whitespace at the ends. With an argument, it splits on exactly that separator:

Python split()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • The optional maxsplit argument limits how many splits happen.
  • .rsplit() counts splits from the right, handy for "everything before the last slash".
  • .splitlines() splits on line breaks of any style (\n, \r\n).

Note: Splitting on commas is fine for simple data, but real CSV files can have commas inside quoted values. Use the csv module for those; see CSV Files.

.join() is the reverse: it glues a list of strings together. It's called on the separator, which surprises people at first:

Python join()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

join() only accepts strings, so numbers must be converted first. The str(n) for n in numbers part converts each one on the fly; it's a generator expression, explained in Dictionary and Set Comprehensions.

A related method, .partition(sep), splits at the first separator and always returns three parts: before, separator, after. It's convenient for key=value pairs:

Python
key, _, value = "timeout=30".partition("=")
print(key, value)   # timeout 30

Finding and replacing

Python find, index, replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • .find(sub) returns the index of the first match, or -1 if there's none. .rfind() searches from the right.
  • .index(sub) does the same but raises a ValueError when nothing is found. Use it when a missing value means something has gone wrong.
  • .replace(old, new) replaces every match; an optional third argument limits the count.
  • .count(sub) counts non-overlapping matches.

If you only need to know whether text appears, "ain" in message is clearer than checking find() != -1.

All of these are case-sensitive. To search regardless of case, lowercase both sides first. For patterns like "any 5 digits" or "a word starting with a capital", use regular expressions.

Checking the start and end

.startswith() and .endswith() return True or False. Both accept a tuple of options to check several at once:

Python startswith and endswith

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

These are clearer and safer than slicing, such as name[-4:] == ".txt", which breaks if the extension length changes.

The is-checks

A family of methods answers yes/no questions about every character in a string. They return False for an empty string.

Method True when every character is...
.isdigit() a digit ("2026")
.isdecimal() a decimal digit (stricter than isdigit)
.isnumeric() any numeric character, including "ยฝ"
.isalpha() a letter ("Ana", "Zoรซ")
.isalnum() a letter or digit ("R2D2")
.isspace() whitespace (" \n")
.isupper() / .islower() upper / lower case (ignoring non-letters)
.isidentifier() valid as a Python name ("user_id")
Python Validating input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that -7 and 3.5 fail: the minus sign and the decimal point aren't digits. The is-checks are good for quick checks such as "is this a PIN made of digits?". To accept any valid number, try converting it with int() or float() and handle the ValueError, as shown in Type Conversion.

Padding and aligning

To line text up in columns, pad it to a fixed width:

Python
print("Total".ljust(10, ".") + "42")    # Total.....42
print("42".rjust(6))                    # '    42'
print("menu".center(12, "*"))           # ****menu****
print("7".zfill(3))                     # 007

.zfill() pads with zeros and keeps a leading sign in place ("-7".zfill(3) gives -07). For most output, f-string alignment is shorter and more flexible; see String Formatting.

Chaining methods

Because each method returns a string, you can call another method on the result directly. This makes cleanup pipelines short and readable:

Python Cleaning a messy list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read a chain from left to right: strip the spaces, then lowercase the result. If a chain gets longer than three or four calls, split it into named steps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "a-b-c".split("-") return?

    split() always returns a list of strings, cut at each separator.
  2. 2. How do you join ["x", "y", "z"] into "x/y/z"?

    join() is a string method called on the separator, with the list as its argument.
  3. 3. What does "banana".find("x") return?

    find() returns -1 when there's no match. index() is the version that raises ValueError.
  4. 4. What does "report.csv".strip(".csv") return?

    strip() removes any of the given characters from both ends. Here it removes v, s, c and the dot from the right, then stops at t. It happens to work, but removesuffix(".csv") is the reliable way, since strip would also eat a trailing s or c from a name like "docs.csv".
  5. 5. Which check is True for the string "2026"?

    Every character in "2026" is a digit, so isdigit() returns True.

Summary

  • String methods return new values; assign the result to keep it.
  • Case: upper(), lower(), title(), capitalize(), and casefold() for comparisons.
  • Trimming: strip(), lstrip(), rstrip() remove characters from the ends; removeprefix() and removesuffix() remove exact text.
  • split() turns a string into a list; "sep".join(list) turns a list of strings back into one string. partition() and splitlines() are handy relatives.
  • Searching: find() (returns -1), index() (raises), count(), replace(), plus the in operator.
  • startswith() and endswith() accept a tuple of options.
  • isdigit(), isalpha(), isalnum(), isspace() and friends check every character.

Next: String Formatting, where you'll make f-strings do the alignment, rounding and number formatting for you.