Working with strings
Index, slice and clean text, build it with f-strings, and use the common string methods.
17 min
A string is a sequence of characters. Each character has a position, an index, and the first one is 0.
word = "python"
print(word[0]) # p
print(word[5]) # n
print(word[-1]) # n (negative counts from the end)
print(len(word)) # 6word[start:stop] takes the characters from start up to, but not including, stop. Leave one out to go to the end:
word[0:2] # 'py'
word[2:] # 'thon'
word[:3] # 'pyt'
word[::-1] # 'nohtyp' (step -1 reverses)| Method | Does |
|---|---|
s.upper(), s.lower() | change case |
s.strip() | remove spaces at both ends |
s.split() | break on whitespace into a list of words |
s.replace("a", "b") | swap every a for b |
s.startswith("py") | True or False |
s.find("th") | index of the first match, or -1 |
Put an f before the quotes and write any expression inside {}:
name = "Ada"
score = 92.5
print(f"{name} scored {score:.1f}%") # Ada scored 92.5%:.1f means one decimal place. f-strings are the clearest way to mix text and values.
“`word.upper()` changes `word`.”
The name sounds like an action on the string, and in many languages a method changes the object.
What is actually true
Strings can never be changed. Every method returns a new string and leaves the original alone. To keep the result, store it: word = word.upper().
How to catch yourself
If a string method seems to do nothing, you probably forgot to use or save its return value.
Build a tidy greeting from messy input, one step at a time.
Start with the raw text
Imagine the user typed
" aDa loVElace ": extra spaces and odd capitals.Strip, then fix the case
raw.strip().title()gives"Ada Lovelace". Methods chain left to right, each working on the result of the one before.Take the first word
clean.split()[0]splits into["Ada", "Lovelace"]and takes index 0.Write it with an f-string
print(f"Welcome, {first}!")printsWelcome, Ada!.
Write initials(full_name) that returns the initials of a name, each followed by a full stop, in capitals.
initials("Ada Lovelace") is "A.L.". Extra spaces and lowercase must not matter.
Your code must satisfy
- initials("Ada Lovelace")→"A.L."two names
- initials("grace brewster hopper")→"G.B.H."three names
- initials(" alan turing ")→"A.T."extra spaces
- initials("Plato")→"P."one name
def initials(full_name):
passRead one line of text. Print it in capitals, then on the next line print how many characters it has, like this:
HELLO THERE
11 charactersYour code must satisfy
- two words
- one word
text = input()- Indexes start at 0, and negative indexes count from the end.
s[a:b]includesaand excludesb.- String methods return new strings: store the result if you want it.
- f-strings (
f"{value}") are the cleanest way to put values inside text.
Quick checks on strings.
What is "python"[1:4]?
- A`"pyt"`
- B`"yth"`
- C`"ytho"`
- D`"tho"`
What is "banana".replace("a", "o")?
- A`"bonono"`
- B`"bonana"`
- C`"banono"`
- D`"banana"`
What is len("hello world")?
To get the last character of s, write s[].
Capitalisation, spacing and punctuation are ignored when grading.
After s = "hi" and s.upper() on its own line, what is s?
- A`"HI"`
- B`"hi"`
- CNone
- DAn error
Pick a short message you sent today. What would you use `.split()`, `.lower()` or slicing for if a program had to read it?
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.