Strings as sequences

A string is a sequence of characters, indexed like a list

s = 'Python'P0-6y1-5t2-4h3-3o4-2n5-1s[0] is 'P's[-1] is 'n's[1:4] is 'yth's[::-1] is 'nohtyP'len(s) is 6'th' in s is TrueA string is a sequence of characters, indexed like a list.Everything you know about list indexes and slices carries over: from 0, from -1 at the farend, and a slice that stops before its stop. A slice of a string is a string. in asks whetherone string appears inside another.

s[0], s[-1], s[1:4]. A slice of a string is a string.

Strings as sequences · Going deeper

Quotes and escape sequences

You writeThe string holdsNote'hello' "hello"helloSingle or double quotes: no difference"It's" 'It\'s'It'sUse the other quote, or escape it with a backslash'a\nb'a, new line, b\n is one character: len is 3'a\tb'a, tab, b\t is one character: len is 3'C:\\dir'C:\dir\\ is one backslash'''oneone, new line, twoTriple quotes may run over several lines;two'''the line break is kept: len is 7A backslash and the character after it count as one character.That is the escape sequence. So len('a\nb') is 3, not 4.

\n and \t are one character each.

Immutability

A string cannot be changed, only replaced

s = 'cat's.upper()print(s)s = s.upper()print(s)sprinted'cat''cat'the new string 'CAT' is thrown away'cat'cat'CAT'the name s moves to the new string'CAT'CATA string cannot be changed, only replaced.s.upper() does not alter s. It builds a new string and returns it. If you do not keep theresult, nothing has happened. s[0] = 'b' is a TypeError, for the same reason as with a tuple.

Methods return a new string. Keep it, or lose it.

Immutability · Going deeper

Operators on strings

CodeGivesNote'abc' + 'def''abcdef'+ joins'ab' * 2'abab'* repeats'P' not in 'Python'Falsein and not in look for a substring'apple' < 'banana'TrueCompared letter by letter'Zebra' < 'apple'TrueCapitals come before small letters'abc'[5]IndexErrorAn index past the end'abc'[1:10]'bc'A slice past the end is not an errorfor ch in 'hi':h, then iA loop gets one character at a timeStrings behave like tuples of characters: readable in every way, changeable in none.

+, *, in, <.

Check yourself

s = 'Python'print(s[1:3] + s[-1])

What does this print?

String methods

Every string method returns a new string

'Hello World'.lower()'hello world'all small'Hello World'.upper()'HELLO WORLD'all capitals'Hello World'.swapcase()'hELLO wORLD'each letter flipped'hello world'.title()'Hello World'a capital on every word'hello world'.capitalize()'Hello world'a capital on the first onlyEvery string method returns a new string.The original is never touched. title() and capitalize() are the pair to keep apart: onecapitalises each word, the other only the first letter of the whole string.

lower(), upper(), swapcase(), title(), capitalize().

String methods · Going deeper

find(), replace() and strip()

CodeGivesNote'hello'.find('l')2The index of the first match'hello'.find('z')-1Not found is -1, not an error'banana'.replace('a', 'o')'bonono'Every match is replaced' hi '.strip()'hi'Spaces removed from both ends' hi '.lstrip()'hi 'From the left end only' hi '.rstrip()' hi'From the right end only'xxhixx'.strip('x')'hi'Or strip a character you namefind() answers with a position. in answers with True or False.strip() only ever works on the ends. Spaces in the middle of a string stay.

find() gives -1 if absent. strip() trims the ends.

split() and join()

split() cuts a string into a list. join() glues it back.

'a,b,c'one string.split(',')'a''b''c'a list of three strings'-'.join(...)'a-b-c'one string againsplit() cuts a string into a list. join() glues a list into a string.split(',') cuts at every comma and drops the commas. With no argument, split() cuts at anyrun of spaces. join() is called on the separator, not on the list: '-'.join(parts) puts ahyphen between the items. The items must all be strings.

split(): str to list. join(): list to str.

split() and join() · Going deeper

Chained methods

' Ada '.strip().lower()methods run left to right'Ada'.lower()strip() first'ada'then lower()'a,b'.split(',')[1].upper()['a', 'b'][1].upper()split gives a list'b'.upper()index 1 of it'B'Each step works on the result of the one before.

Left to right. Each works on the result before.

Check yourself

s = ' a-b-c 'parts = s.strip().split('-')print(len(parts), parts[-1])

What does this print?

Formatting

An f-string fills its braces with values

name = 'Ada'age = 36f'{name} is {age}''Ada is 36'an f-string: names inside the braces'{} is {}'.format(name, age)'Ada is 36'format(): braces filled in order'%s is %d' % (name, age)'Ada is 36'the older % operatorf'{age + 1}' is '37': a replacement field can hold any expressionAn f-string fills its braces with values.Put f before the opening quote. Without it the braces are ordinary text.

f'{name}', .format(), %.

Formatting · Going deeper

More formatting

name, age, pi = 'Ada', 36, 3.14159CodeGivesNotef'{pi:.2f}''3.14'After a colon: two decimal places'{1} {0}'.format('a', 'b')'b a'A number picks an argument by position'{n} is {a}'.format(n=name, a=age)'Ada is 36'Or by name'%.1f' % pi'3.1'%s text, %d whole number, %f float'{name} is {age}''{name} is {age}'No f: nothing is filled inf'{{x}}''{x}'Doubled braces give a real braceAll three ways build a str. The values themselves are not changed.A formatted number is text: f'{age}' + 1 is a TypeError.

:.2f for decimals. No f, no filling.

Check yourself

x = 3y = 4print(f'{x} + {y} = {x + y}')

What does this print?

Lesson complete

You finished “Strings”

Answer the questions along the way to see your score here.

Open in a new tab