Data types · 6 / 29 Theory

String methods

Strings come with many built-in tools, called methods, to transform and examine them. You call them by writing a dot after the string: text.method().

Changing upper and lower case

t = "hello world"
print(t.upper())        # HELLO WORLD
print("Hello".lower())   # hello
print(t.title())        # Hello World   (each word capitalized)
print(t.capitalize())   # Hello world   (only the first letter)

Removing extra spaces

strip() removes spaces (and line breaks) from the beginning and the end. It is very useful with what a user types:

text = "  Hello World  "
print(text.strip())    # Hello World
print(text.lstrip())   # Hello World  (left side only)
print(text.rstrip())   #   Hello World (right side only)

Searching, counting and replacing

MethodWhat it doesExample with t = "hello world"
find(piece)Position where it appears; -1 if it is not theret.find("world") → 6
count(piece)How many times it appearst.count("o") → 2
replace(a, b)Replaces a with bt.replace("o", "0") → hell0 w0rld
startswith(x)Does it start with x?t.startswith("he") → True
endswith(x)Does it end with x?t.endswith("ld") → True

Splitting and joining

split() splits the text into a list of words; join() does the opposite:

print("one two three".split())     # ['one', 'two', 'three']
print("a,b,c".split(","))           # ['a', 'b', 'c']
print("-".join(["a", "b", "c"]))       # a-b-c

Without arguments, split() separates by spaces and already copes with several in a row. With len(text.split()) you get the number of words.

Checking the content

print("123".isdigit())      # True   (digits only)
print("abc123".isdigit())   # False
print("hello".isalpha())    # True   (letters only)

Methods do not modify the original string

Since strings are immutable, a method returns a new string. If you want to keep the result, store it:

name = "ana"
name.upper()          # the result is lost
print(name)           # ana

name = name.upper()   # now it is stored
print(name)           # ANA

Chaining methods

Since each method returns a string, you can chain several on one line:

entry = "  PYTHON is Great  "
print(entry.strip().lower())   # python is great

Practice in the exercises about a text profile and spaces to hyphens.