Text in Python is called a string. In this course you count the letters, pick out single letters and pieces, change the case, clean messy text, join and repeat text, put values inside sentences with f-strings, ask questions about text, and search inside it. You finish with a name tag maker and a small text analyser. Every lesson has practice that checks your answers.
5 lessons, about 2 h 35 min5 simulations13 problems10 practice questionsPython in every lesson
A string is a row of characters inside quotation marks. len() gives the number of characters, including spaces. Every character has a position, and the first position is 0. Square brackets pick one character: word[0] is the first and word[-1] is the last. A position that is too big gives an IndexError. A string cannot be changed in place, so to change one we make a new string and store it in the name.
A slice such as word[2:5] takes the characters from position 2 up to, but not including, position 5. word[:3] starts at the beginning, word[3:] goes to the end, and word[::-1] gives the word backwards. String methods such as upper(), lower(), title(), strip() and replace() give a new, changed string and leave the old one as it was. strip() is useful to clean the spaces that a user types by mistake.
The + sign joins two strings and the * sign repeats a string. A number must be changed to text with str() before it is joined with +. An f-string puts values inside text: write f before the opening quotation mark and put the names or sums in curly brackets. After a colon inside the brackets we can say how to show the value: :.2f gives two decimal places, and :>8, :<8 and :^8 align the text in a width of 8.
A string can answer questions. The word in tells whether a piece of text is inside another text. startswith() and endswith() test the two ends, and isdigit(), isalpha() and isupper() test what kind of characters it has. These give True or False. count() counts how many times a piece occurs, find() gives the position of the first match or -1, and index() does the same but stops with an error when the piece is missing.
In this project we write two programs with strings. A name tag maker centres a name and a role inside a border whose width is set by the longer of the two lines, using len(), max(), text times a number and f-string alignment. A text analyser counts the characters, the words and the vowels of a sentence, finds the first word with find() and slices, and shows the sentence in capital letters and reversed. We plan each one, test it with a text that we can check by hand, and then change it.
Log in to join the discussion.
Loading…