3.7 String Methods

3.7.1 .upper() and .lower()

The .upper() and .lower() methods take a string and convert it to uppercase and lowercase, respectively.

print("out on the wily, windy moors".upper())
## OUT ON THE WILY, WINDY MOORS
aria = "PiangerĂ² La Sorte Mia"
print(aria.lower())
## piangerĂ² la sorte mia

3.7.2 .split()

The .split() method takes a string and splits it into a list, dividing the list on a delimiter (i.e., separator). The delimiter is provided as an argument:

print("Newt eye, frog toe".split(','))
## ['Newt eye', ' frog toe']

If no argument is provided, then the string is split on whitespace (that is, it is split whenever a space or tab is encountered).

print("Eye of newt    and toe of frog".split())
## ['Eye', 'of', 'newt', 'and', 'toe', 'of', 'frog']

3.7.3 .join()

The .join() method is the inverse of .split(): converts a list into a string, with list elements separated by a delimiter. The general syntax is:

"<delimiter>".join(<list>)

For example:

" ".join(["I", "found", "a", "fox", "caught", "by", "dogs"])
## 'I found a fox caught by dogs'

If we do not provide a delimiter, then the strings are directly concatenated:

"".join(["I", "found", "a", "fox", "caught", "by", "dogs"])
## 'Ifoundafoxcaughtbydogs'

3.7.4 .rstrip(), .lstrip(), .strip()

These three methods remove unwanted characters on the right, left, or both sides of a string. You can provide the characters you want to remove as an argument:

"ricercar........,,,,,,".rstrip(",.")
## 'ricercar'

Without an argument, the methods remove spaces:

"          ricercar ".lstrip()
## 'ricercar '

Note that in the above example we strip the spaces to the left of the main text, but we do not remove the spaces from the middle or right end of the text.