Summary
In this lesson, you learned that:
- Text has methods of its own. A text can't be changed, so a method never changes it: it returns a new text, and the original stays as it was. Store the result or use it right away:
name = name.strip(). upper()andlower()turn all letters into uppercase or lowercase, andcapitalize()makes the first character uppercase and all the others lowercase. To compare without caring about case, turn both texts into lowercase:a.lower() == b.lower().strip()removes the spaces at the start and end of a text, such as those a person typed by accident. Methods can be chained:typed.strip().lower().replace(old, new)replaces every place whereoldappears.replace(" ", "")removes the spaces.part in textisTrueif the text contains the part anywhere (in a list,inlooks for a whole element).find()returns the index where the part starts, or-1, andcount()how many times it appears.startswith()andendswith()check the start and the end of a text. All of them care about case.split()splits a text into a list: at the spaces, or at the separator in the parentheses,"12,7,30".split(","). The parts are texts, so numbers needint().", ".join(names)joins a list of texts into one text, with the separator between the elements. Only texts can be joined: turn numbers into texts withstr()first.- A slice is a part of a text or a list:
text[2:5]goes from index 2 up to index 5, without index 5.text[:3]is the first three characters,text[2:]everything from index 2 on,text[-3:]the last three.scores[:3]is the first three elements of a list. A slice never ends with anIndexError. - Decimal places:
f"{price:.2f}"prints a number with two decimal places,f"{average:.1f}"with one. It rounds only what is printed; the variable keeps its value.
Now put it all together. Players have signed up for a tournament by typing their names into one text, separated by commas, each the way they liked.
In the next lesson, Tuples and Sets, you'll meet two more ways of keeping several values together: tuples, for values that belong together and don't change, and sets, which keep each value only once.
Instructions
- 1
Make a list
playersof the names, each without the spaces around it and with only its first letter in uppercase. Then print the players on one line, separated by a comma and a space:Players: Anna, Tom, Eva, Max. Keep the line withsignups: the exercise also tries other sign-ups in it. - 2
The first three players to sign up get a T-shirt. Take them from
playerswith a slice and print them the same way:T-shirts: Anna, Tom, Eva.