Strings as sequences
A string is a sequence of characters, indexed like a list
s[0], s[-1], s[1:4]. A slice of a string is a string.
A string is text, and Python treats it as a row of characters. Each character has an index from zero, and a negative index from the far end. So s zero is capital P, and s minus one is n. Slices work as they do for lists. One to four gives y, t, h. A step of minus one reverses the string. Len counts the characters, and in looks for one string inside another.
Strings as sequences · Going deeper
Quotes and escape sequences
\n and \t are one character each.
Immutability
A string cannot be changed, only replaced
Methods return a new string. Keep it, or lose it.
Strings are immutable, like tuples. Watch what that means for a method call. s is cat. s dot upper builds a new string, in capitals. Nobody keeps it. s is still cat. So this prints cat. Now the result is assigned back to s. The name moves to the new string. And this prints cat in capitals.
Immutability · Going deeper
Operators on strings
+, *, in, <.
Check yourself
What does this print?
String methods
Every string method returns a new string
lower(), upper(), swapcase(), title(), capitalize().
Five methods deal with capitals. Lower makes every letter small. Upper makes every letter a capital. Swapcase flips each one. Title gives every word a capital. Capitalize gives a capital to the first letter of the string only, and makes the rest small.
String methods · Going deeper
find(), replace() and strip()
find() gives -1 if absent. strip() trims the ends.
split() and join()
split() cuts a string into a list. join() glues it back.
split(): str to list. join(): list to str.
Two methods move between a string and a list of strings. Start with one string that has commas in it. Split it at the commas, and you get a list of three strings. The commas are gone. Join does the reverse. You call it on the separator, here a hyphen, and hand it the list.
split() and join() · Going deeper
Chained methods
Left to right. Each works on the result before.
Check yourself
What does this print?
Formatting
An f-string fills its braces with values
f'{name}', .format(), %.
Python has three ways to put values into text, and the exam expects you to read all of them. The f string: an f before the quote, and the names inside braces. The format method: empty braces, filled in order by its arguments. And the percent operator, the oldest: percent s for text, percent d for a whole number. All three give Ada is thirty six. The braces of an f string can hold a calculation too.
Formatting · Going deeper
More formatting
:.2f for decimals. No f, no filling.
Check yourself
What does this print?
Lesson complete
You finished “Strings”
Answer the questions along the way to see your score here.