Python String Methods
A method is a function that belongs to a value. You call it with a dot after the value: name.upper(). Strings have dozens of methods for changing case, cleaning text, searching and splitting. Because strings cannot change, every method that "changes" a string actually returns a new one; you keep it by assigning it to a variable.
Case and spaces
text = " hello, PYTHON world "
print(text.upper())
print(text.lower())
print(text.strip())
print(text.strip().title())
print(text.strip().capitalize())
print("[" + text.lstrip() + "]")HELLO, PYTHON WORLD hello, python world hello, PYTHON world Hello, Python World Hello, python world [hello, PYTHON world ]
strip removes spaces (and new lines and tabs) at both ends; lstrip and rstrip remove them only on the left or the right. It is the first thing to do with text a user typed or a line read from a file. title starts every word with a capital letter, and capitalize only the first word.
Searching and replacing
sentence = "the cat sat on the mat"
print(sentence.replace("cat", "dog"))
print(sentence.count("the"))
print(sentence.find("sat"), sentence.find("bus"))
print(sentence.startswith("the"), sentence.endswith("mat"))the dog sat on the mat 2 8 -1 True True
find gives the index where the text starts, or -1 when it is not there. replace changes every occurrence; give a third number, replace("a", "b", 1), to change only the first ones.
Splitting and joining
split cuts a string into a list of parts, and join glues a list of strings back together with a separator between them. Together they are the everyday tools for handling text data:
line = "Asha,21,Pune"
parts = line.split(",")
print(parts)
words = "learn python step by step".split()
print(len(words), "words")
print("-".join(words))
print(" | ".join(["a", "b", "c"]))['Asha', '21', 'Pune'] 5 words learn-python-step-by-step a | b | c
split() with no argument splits on any run of spaces and ignores spaces at the ends.
Checking what a string contains
Methods whose names start with is answer yes-or-no questions: "2026".isdigit() is True, "abc".isalpha() is True, "Python3".isalnum() is True and " ".isspace() is True. They are handy for checking input before you convert it.
Practice exercises
- Ask nothing yet; just take
" Asha Rao ", strip it and print it in upper case and in title case. - Count how many times the letter
aappears in"banana bandana". - Split the date
"21-10-2026"into day, month and year, and print them as2026/10/21usingjoin. - Check with
isdigitwhether"42","4.2"and"-42"are made only of digits.