← Python lessons

String Methods

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A string method is an action you call on text with a dot, as in name.upper(). String methods change case, replace text or split text into parts.

upper and lower

name = "Sanjin"print(name.upper())print(name.lower())

.upper() gives the text in capitals. .lower() gives it in lowercase.

replace

sentence = "I like cats"print(sentence.replace("cats", "dogs"))print(sentence)

.replace(old, new) swaps every old for new. Matching is case-sensitive, so "Cats" would not match "cats".

The second line still prints I like cats. A method gives back a new string and leaves the original alone. To keep the change, save it:

sentence = "I like cats"sentence = sentence.replace("cats", "dogs")print(sentence)

split

.split() cuts text at the spaces and gives back a list of the pieces.

line = "7 10 2 9"cards = line.split()print(cards)print(len(cards))

Each piece is still a string: "7", not 7.

See also: Indexing, String Formatting, Lists.

Your turn

Print the title in capitals, then print it with great replaced by small.

🎯 Goal — make it print exactly:
THE GREAT ESCAPE
the small escape
title = "the great escape"# print the title in capitals, then with "great" replaced by "small" (two lines)

Advanced reading