Strings
You have used strings since your first line of code, and you know the six sequence tricks work on them. Now meet what strings can do that is theirs alone — the methods. And watch closely, because every one of them hands back a new string and leaves the old one exactly as it was.
1What you already know
A string is a sequence of characters in quotes. Single, double or triple quotes — you chose them back in the print chapter. And because it is a sequence, all six common features apply:
word = 'hello'
print(len(word))
print(word[0])
print(word[-1])
print(word[1:4])
print('hi' + 'there')
print('ha' * 3)
print('ell' in word)5 h o ell hithere hahaha True
2Methods: a string's own tricks
A method is a function that belongs to a value. You write it after the value, with a dot in between: 'hello'.upper(). Same parentheses as always, so you already know it is a function — it just happens to belong to that string.
len('hello') — the string goes inside the parentheses. That is a function. 'hello'.upper() — the string comes before the dot. That is a method. Same idea, different way of writing it.String methods come in four kinds, sorted by the question you are asking. Try each one, and keep half an eye on the amber box on the right.
A new string, every letter in CAPITALS.
Untouched. Every single time. A method never edits the string it was called on — it builds something new and hands that back.
capitalize() puts one capital at the very front and makes everything else small — so 'RAMESH KUMAR'.capitalize() gives 'Ramesh kumar'. title() capitalises the first letter of every word — so 'ramesh kumar'.title() gives 'Ramesh Kumar'. One is a sentence; the other is a name.strip() is worth remembering. A space at the end of a word is invisible, and it still counts. If a user types yes with a stray space after it, then 'yes ' == 'yes' is False — and your program says no when the user said yes. strip() takes the blank space off both ends and hands back a clean string, so ' yes '.strip() == 'yes' is True. Spaces inside are left alone: ' a b '.strip() gives 'a b', keeping the one in the middle. Need only one side? lstrip() cleans the left, rstrip() the right.The trouble with showing this is that spaces are invisible. So print each answer between square brackets — then you can see exactly where the string ends:
typed = ' Ravi '
print('[' + typed.strip() + ']')
print('[' + typed.lstrip() + ']')
print('[' + typed.rstrip() + ']')
print('[' + typed + ']')[Ravi] [Ravi ] [ Ravi] [ Ravi ]
rstrip() is the right end — R for RIGHT. It cleaned the two spaces after Ravi and left the two before it exactly as they were. And the last line proves the point of this whole lesson: typed itself still has spaces on both sides. Not one of the three methods edited it — each handed back a new string.replace() is the one that takes two things: what to look for, and what to put in its place. It changes every match it finds, not just the first one:
greeting = 'good morning'
print(greeting.replace('o', '0'))
print(greeting.replace('morning', 'evening'))
print(greeting)g00d m0rning good evening good morning
All three os went, because replace() does not stop at the first one. And look at the last line: greeting is still 'good morning'. Like every method on this page, replace() hands you a new string and leaves the original exactly as it was.
toupper() or tolower() in Python. Those are from other languages (C, C++, Java), and students who have seen them elsewhere type them by habit. Python uses upper() and lower(). Write 'hello'.toupper() and you will get AttributeError: 'str' object has no attribute 'toupper'.3The is-methods: asking, not changing
These all begin with is, and they all answer True or False. They never change anything — they only look and report.
| Method | Asks | Example |
|---|---|---|
isupper() | Is it ALL in capitals? | 'HELLO'.isupper() → True |
islower() | Is it all in small letters? | 'Hello'.islower() → False |
isalpha() | Is every character a letter? | 'hello'.isalpha() → True |
isdigit() | Is every character a digit? | '12345'.isdigit() → True |
isspace() | Is it nothing but blank space? | ' '.isspace() → True |
isalnum() | Is every character a letter or a digit? | 'abc 123'.isalnum() → False |
upper() makes a capitalised copy. isupper() only asks whether it already is — and answers True or False. Change versus ask.'abc 123'.isalnum() is False, because a space is neither a letter nor a digit. In the same way '12a'.isdigit() is False — one letter is enough to spoil it — and 'hello world'.isalpha() is False, because of the single space in the middle.4find() and index() — the same, until they fail
Both tell you where something is. When the thing is there, they give exactly the same answer:
word = 'hello'
print(word.find('l'))
print(word.index('l'))2 2
The difference only appears when the thing is not there — and it is a big one:
word = 'hello'
print(word.find('z')) # not there -> -1, and the program carries on
print(word.index('z')) # not there -> the program stops here-1
Traceback (most recent call last):
File "finding.py", line 4, in <module>
print(word.index('z')) # not there -> the program stops here
^^^^^^^^^^^^^^^
ValueError: substring not foundfind() is polite: not there? It shrugs and returns -1, and your program carries on. index() is strict: not there? It raises a ValueError and stops. Use find() when the thing might be missing. Use index() when it should never be.Sometimes you do not need to know where something is — only whether the string begins or ends with it. That is what startswith() and endswith() are for, and they answer True or False:
name = 'Ramesh Kumar'
filename = 'report.txt'
print(name.startswith('Ram'))
print(name.endswith('Kumar'))
print(filename.endswith('.txt'))
print(name.startswith('ram'))True True True False
'Ramesh Kumar' does begin with ram as far as your eye is concerned, but the answer is False — a capital R and a small r are two different characters. Every string method that compares letters works this way. If the capitals do not matter to you, compare in one case: name.lower().startswith('ram') is True.5split(), partition() and join()
These three move between a string and a list. split() and partition() break a string apart; join() glues it back together.
letters = 'a,b,c'.split(',')
parts = 'good morning'.partition(' ')
joined = '-'.join(['a', 'b', 'c'])
print(letters)
print(parts)
print(joined)['a', 'b', 'c']
('good', ' ', 'morning')
a-b-cGives back a list of the pieces. The separator itself is thrown away.
Gives back a tuple of three: what came before, the separator itself, and what came after. Nothing is thrown away.
'-'.join(['a', 'b', 'c']). Read it aloud as: “using a dash, stick these together”. Almost everybody writes it the other way round the first time.6Try it at the prompt
7The original never changes
This is the most important sentence in the lesson. A string method never edits the string it was called on. It builds a new string and gives that back.
word = 'hello'
print(word.upper()) # a new string comes back
print(word) # the original is untouchedHELLO hello
Look at that carefully. We shouted at 'hello', and it politely handed back a capitalised copy. Then we asked for 'hello' again — and it is still small, still itself, entirely unbothered.
upper() do not change it — they return a new string. This has a proper name, immutable, and it gets a lesson of its own shortly.8in — is it in there?
This one is not a string method at all — it is the membership operator from the sequences lesson, and it works on lists and tuples too. Ask whether a character (or a smaller piece of text) appears inside a string. The answer comes back as a boolean — True or False. Unlike find(), it does not tell you where — only whether.
word = 'hello'
print('e' in word)
print('z' in word)
print('ell' in word)True False True
9Escape sequences — the backslash
An escape sequence is a short code you write inside a string. It always begins with a backslash (\), followed by one or more characters. You type two symbols, but Python does not read them one by one — it treats the pair as one single character, and each pair has one fixed job.
\ — the backslashWarns Python: do not read the next character in the usual way.
n — the code letterSays which special character you want. n is a new line, t is a tab.
They exist because some characters cannot simply be typed. Here is the smallest example. You want to print It's mine, so you write it in single quotes:
print('It's mine') File "quotes.py", line 1
print('It's mine')
^
SyntaxError: unterminated string literal (detected at line 1)Python is not being difficult. It read the second quote — the one in It's — and decided the string ended there. Everything after it made no sense.
The fix is the backslash. Write \' and Python knows that quote is part of the text, not the end of it.
print('It\'s mine') # \' means: a plain quote, not the end
print("It's mine") # or just use the other kind of quotes
print("He said \"hi\"")It's mine It's mine He said "hi"
The same backslash does a second job. Some characters cannot be typed inside a string at all — you cannot press Enter in the middle of one, and you cannot type a Tab and expect it to survive. So Python gives you short codes for them.
| You write | You get | Used for |
|---|---|---|
\n | a new line | moving to the next line |
\t | a tab | lining up columns |
\\ | one backslash | when you really want a \ |
\' | a single quote | inside a '...' string |
\" | a double quote | inside a "..." string |
\b | a backspace | rare, but in your syllabus |
\r | a carriage return | back to the start of the line |
\0 | a null character | rare, but in your syllabus |
\n and \t are the two you will actually use. One breaks a line, the other lines things up in columns:
print('Name\tClass\tMarks')
print('Ramesh\t11\t87')
print('line one\nline two')Name Class Marks Ramesh 11 87 line one line two
len('\n') is 1, and len('a\nb') is 3. This is a favourite exam question.newline = '\n'
tab = '\t'
backslash = '\\'
print(len(newline))
print(len(tab))
print(len(backslash))
print(len('a\nb'))1 1 1 3
The trap: Windows file paths
Windows writes paths with backslashes, like C:\notes\table.txt. Put that straight into a string and Python reads \n and \t as escape sequences — and your path falls apart.
path = 'C:\notes\table.txt'
print(path) # \n became a new line, \t became a tab!
safe = 'C:\\notes\\table.txt'
print(safe) # doubled backslashes: correct, but ugly
raw = r'C:\notes\table.txt'
print(raw) # an r in front: much easierC: otes able.txt C:\notes\table.txt C:\notes\table.txt
r in front of a string makes it a raw string: every backslash inside stays exactly as you typed it, and no escape sequence is applied. Handy for file paths.10Recap
| Method | Does | Gives back |
|---|---|---|
upper() | ALL CAPITALS | a new string |
lower() | all small letters | a new string |
capitalize() | First letter only — rest made small | a new string |
title() | First Letter Of Each Word | a new string |
strip() | removes spaces at both ends | a new string |
lstrip() / rstrip() | left end only / right end only | a new string |
replace(a, b) | swaps every a for b | a new string |
isupper() | is it ALL capitals? | True / False |
islower() | is it all small letters? | True / False |
isdigit() | is every character a digit? | True / False |
isspace() | is it only blank space? | True / False |
isalpha() | is every character a letter? | True / False |
isalnum() | letters and digits only? | True / False |
startswith(x) | does it begin with x? | True / False |
endswith(x) | does it end with x? | True / False |
count(x) | how many times x appears | a number |
find(x) | position of first x — gives -1 if absent | a number |
index(x) | position of first x — ERROR if absent | a number |
split(sep) | cuts at every separator | a list |
partition(sep) | cuts at the first separator only | a tuple of 3 |
sep.join(list) | glues a list into one string | a new string |
And the escape sequences — every one of them a single character:
| Escape sequence | Gives you | Length |
|---|---|---|
\n | a new line | 1 character |
\t | a tab | 1 character |
\\ | one backslash | 1 character |
\' | a single quote, inside '...' | 1 character |
\" | a double quote, inside "..." | 1 character |
\b | a backspace | 1 character |
\r | a carriage return | 1 character |
\0 | a null character | 1 character |
'hello'.upper(). String methods always return a new value; the original string is never edited. An escape sequence is written inside the string itself: two symbols starting with \, stored as one character. Put r in front of a string to switch them all off.After 'hello'.upper(), what is 'hello'?
What does 'hello'.count('l') give?
Which is a method, not a function?
'hello'.find('z') gives -1. What does 'hello'.index('z') do?
What does 'RAMESH KUMAR'.capitalize() give?
What is 'abc 123'.isalnum()?
How do you join ['a', 'b', 'c'] into 'a-b-c'?
What is len('a\\nb')?
What does print('C:\\notes') show?