String methods
The official documentation provides a complete list of str
methods.
You can also get a (shorter) documentation with help()
help(str) # displays the documentation for the str class
help(str.lower) # displays the documentation for the lower() method of str
We will not cover all the methods, but only a few that you may find useful. We will leave you to read the documentation yourself.
str.startswith(s)
and str.endswith(s)
name = "Gordon Ramsay"
if name.startswith("a"):
print(f"{name} starts with a")
if name.endswith("y"):
print(f"{name} ends with y")
str.upper()
, str.lower()
, str.capitalize()
, str.title()
, str.swapcase()
name = "maRy BErrY"
print(name.upper()) # MARY BERRY
print(name.lower()) # mary berry
print(name.capitalize()) # Mary berry
print(name.title()) # Mary Berry
print(name.swapcase()) # MArY beRRy
There are also str.isupper()
, str.islower()
and str.istitle()
methods to check whether these are True
.
Testing whether all characters in strings are a certain type
print("hahaha".isalpha())
print("90210".isdigit())
print("haha90210".isalnum()) # alphanumeric characters
print(" \n ".isspace()) # all characters are whitespace
Whitespace removal: str.strip()
This will remove any leading or trailing whitespace. Useful for removing any extra spaces and newlines from the beginning and end of sentences.
Use an interactive prompt to be able to see the whitespace.
>>> s = " pen pineapple apple pen \n "
>>> s.strip()
'pen pineapple apple pen'
>>> s.lstrip() # strip leading whitespace only
'pen pineapple apple pen \n '
>>> s.rstrip() # strip trailing whitespace only
' pen pineapple apple pen'
You can also define the set of characters to be stripped.
>>> 'www.example.com'.strip('cmowz.')
'example'
str.split()
Splits a string into a list of substrings.
word_list = "London Bridge is falling down".split()
print(word_list)
number_list = "10,20,30,10,5,1".split(",")
print(number_list)
Use the keyword argument maxsplit
if you want to limit the number of substrings (see documentation).
str.join()
Joins a sequence of strings with a given separator. Check the output yourself if you want to see them! 😀
joined_string = " ".join(["10", "20", "30", "10", "5", "1"])
print(joined_string)
joined_string = ",".join(["10", "20", "30", "10", "5", "1"])
print(joined_string)
joined_string = ", ".join(["10", "20", "30", "10", "5", "1"])
print(joined_string)
joined_string = "--".join(["10", "20", "30", "10", "5", "1"])
print(joined_string)
str.replace(old, new)
Replace occurrences of old
in str
with new
. You can specify the maximum number of occurrences to replace with a thrid optional argument (see documentation).
sentence = "one little two little three little indians"
sentence.replace("little", "big")
print(sentence)
Searching for substrings in a string
Use the in
operator to check whether a substring in in a string
print("at" in "the cat is in the mat")
If you need to know where the first match occurs, then use str.find(substring)
or str.index(substring)
. What is the difference between the two? Find out from the documentation! 😉 It also describes a few more optional arguments.
sentence = "the cat is in the mat"
query = "at"
index = sentence.find(query)
print(index)