Python String Methods
String methods are tools that belong to a string value. A method is called with a dot after the value.
Find a piece
find() gives the starting position of a piece. It gives -1 when the piece is missing, while index() gives an error.
text = "hello world"
print(text.find("world"))
print(text.find("mars"))
print(text.index("world"))Count the repeats
count() tells you how many times a piece appears in the string.
text = "banana"
print(text.count("a"))Check the ends
startswith() and endswith() give True or False for the ends of a string.
filename = "notes.txt"
print(filename.startswith("notes"))
print(filename.endswith(".txt"))Check the characters
These three checks look at every character in the string.
print("123".isdigit())
print("abc".isalpha())
print(" ".isspace())Join words into text
join() takes a list of words and glues them with a separator. The separator is the string before the dot.
words = ["red", "green", "blue"]
print(", ".join(words))More case changes
title() lifts the first letter of each word. capitalize() lifts only the first letter of the string. swapcase() flips every letter.
print("hello world".title())
print("hello WORLD".capitalize())
print("Hello".swapcase())Example
filename = "my notes.txt"
words = ["my", "notes", "draft"]
print(filename.endswith(".txt"))
print(filename.count("t"))
print("-".join(words))Key points
- Use find() to get the position of a piece, or -1 when it is not there
- Use index() like find() to get the position of a piece
- index() raises an error when the piece is missing
- Use count() to count how many times a piece appears
- Use startswith() and endswith() to check the two ends of a string
- Use join() to glue a list of words into one string
- Each string value carries its own set of tools, called methods.
- Some methods answer a question about the string.
- Other methods build a new string from it.
In this example, filename holds the name my notes.txt. The first print checks the end of the name and gives True. count() then counts the letter t, and it appears three times. The last line joins the three words in the list with a dash between them.
Note
The checks isdigit(), isalpha(), and isspace() all give False for an empty string.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does "-".join(["sun", "moon"]) give?