TExcelTAD
Home › Python › Python String Methods

Python String Methods

Strings come with dozens of built-in methods — functions you call with a dot, like text.upper(). Because strings are immutable, every method returns a new string (or another value) and leaves the original untouched.

python · try it yourself
title = "python basics"
print(title.upper())
print(title)            # unchanged
PYTHON BASICS
python basics

Changing case

Method Effect "hello World" becomes
upper() all uppercase HELLO WORLD
lower() all lowercase hello world
title() first letter of each word uppercase Hello World
capitalize() first letter of the string uppercase Hello world
swapcase() swap upper and lower HELLO wORLD
casefold() aggressive lowercase for comparisons hello world

Removing whitespace

Text from users and files often has stray spaces or newlines at the ends. The strip family removes them:

python · try it yourself
raw = "   apple pie  \n"
print("[" + raw.strip() + "]")
print("[" + raw.lstrip() + "]")
print("[" + raw.rstrip() + "]")
print("--==hello==--".strip("-="))   # strip specific characters
[apple pie]
[apple pie  
]
[   apple pie]
hello

Searching

python · try it yourself
sentence = "the cat sat on the mat"
print(sentence.find("at"))       # index of first match
print(sentence.rfind("at"))      # index of last match
print(sentence.find("dog"))      # -1 when not found
print(sentence.count("the"))
print(sentence.startswith("the"))
print(sentence.endswith(("mat", "rug")))   # a tuple means "any of these"
5
20
-1
2
True
True

index() works like find() but raises ValueError instead of returning -1 when nothing is found.

Replacing

replace(old, new) swaps every occurrence; an optional third argument limits how many:

python · try it yourself
s = "one fish two fish red fish"
print(s.replace("fish", "bird"))
print(s.replace("fish", "bird", 1))
one bird two bird red bird
one bird two fish red fish

Splitting and joining

These two are the most useful methods of all. split() breaks a string into a list; join() glues a list of strings back together using the string it's called on as the glue:

python · try it yourself
csv_line = "Hanoi,Hue,Da Nang,Saigon"
cities = csv_line.split(",")
print(cities)

print(" -> ".join(cities))
print("a  b   c".split())          # no argument: split on any whitespace
print("2025-06-01".split("-", 1))  # at most one split

lines = "first\nsecond\nthird".splitlines()
print(lines)
['Hanoi', 'Hue', 'Da Nang', 'Saigon']
Hanoi -> Hue -> Da Nang -> Saigon
['a', 'b', 'c']
['2025', '06-01']
['first', 'second', 'third']

Testing the contents

Methods starting with is return True or False:

Method True when every character is…
isdigit() a digit ("2025")
isalpha() a letter ("abc")
isalnum() a letter or digit ("abc123")
isspace() whitespace
isupper() / islower() upper / lower case (cased letters only)
python · try it yourself
for value in ["123", "12.5", "abc", "abc123", ""]:
    print(repr(value), value.isdigit(), value.isalpha(), value.isalnum())
'123' True False True
'12.5' False False False
'abc' False True True
'abc123' False False True
'' False False False

Notice that an empty string returns False for all of them, and "12.5" is not all digits because of the dot.

Alignment and padding

python · try it yourself
print("|" + "left".ljust(10) + "|")
print("|" + "right".rjust(10) + "|")
print("|" + "mid".center(10, "*") + "|")
print("42".zfill(5))
|left      |
|     right|
|***mid****|
00042

Chaining methods

Because each method returns a new string, you can call another method on the result:

python · try it yourself
messy = "  HeLLo, PyThOn!  "
clean = messy.strip().lower().replace("!", "")
print(clean)
hello, python

Tip: To see every string method, run print(dir(str)) in a playground, or help(str.split) for details on one of them.

Test yourself

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

  1. "abc"
  2. ["a", "b", "c"]
  3. ("a", "b", "c")
  4. ["a,b,c"]

What does "-".join(["x", "y", "z"]) return?

  1. "x-y-z"
  2. "-x-y-z-"
  3. "xyz"
  4. ["x-", "y-", "z"]

What does "hello".find("z") return?

  1. None
  2. 0
  3. -1
  4. It raises ValueError