Course 2.2Lesson 5 of 5
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.
Try the code and the simulations beside the lesson.
After this lesson you can
We want a tag that is wide enough for the name and the role, with the text in the middle, like this:
+------------+
| Asha Rao |
| Student |
+------------+Now test the program. Change name = "Asha Rao" to a very long name, such as "Dr Ananya Venkataraman". Does the tag grow to fit it? Change it to a very short name, "Om". Is the tag still neat? A program that works only for one name is not good enough.
center() adds the spaces for you. When the spaces cannot be shared out equally, the extra one goes to one side.
A text analyser tells you facts about a sentence. We want to know the number of characters, words and vowels, and also the first word, the sentence in capital letters, and the sentence reversed.
len(text).text.count(" ") + 1.a, e, i, o, u in the small-letter version, and add the five numbers.upper(). Reversed: [::-1].A word of care. Counting words with count(" ") + 1 fails when the text has two spaces in a row, or spaces at the ends. A good habit: clean the text first with text.strip().
Choose one, and do it without looking at a solution.
- to =, and the corners to *.text.rfind(" ") gives the position of the last space.input(), and strip() it first.len(). You will count wrong.text.count("a") misses A. Use text.lower().count("a").Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
len() and max() to make a border fit the text.count() and find() answer many questions about a sentence.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
"red green blue" have, by the rule count(" ") + 1?f"{'ab':^6}" show, between square brackets?text.lower().count("a") and not text.count("a") to count the letter A?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.