How can a school race app turn YORK and a runner’s initials AK into the bib code YOAK?
At a school race in York, your team name is York and your initials are A K. The app prints Y O A K on your bib. How can you tell the app which letters to keep and how to join them?
You can pick out a letter by its position. In Python, Y is at zero, O at one, R at two and K at three. So asking for position zero gives you Y. To count all the characters, use len. The length is four, even though the last position is three.
Start with York and put your finger on the Y at position zero. Take two characters in a row, counting the Y as the first. That gives you Y O, the team prefix. A piece taken from consecutive positions in a string is called a substring.
Now start at position one in York and take two characters. Count the character at position one as your first. Which two letters do you get? Pick one answer.
In AQA pseudocode, you give the start and end positions first, then the string. Positions one and two are both included, so you get O R. In Python, you also start at one, but the slice stops before three. You get the same two letters.
Store Leeds and the initials A M. Slice from zero up to, but excluding, three. Print the prefix and check you get L E E. Join it to the initials with plus. That’s concatenation. Print the bib to see L E E A M. The plus sign adds no space.
The team is Bath and the runner’s initials are S T. The slice starts at zero and stops before two. Work out the prefix first, then join it to the initials. Pick the pair that shows both results.
You’ve used A as a runner’s initial. Python can give you the number that represents that character. Ord turns capital A into its Unicode code, sixty-five. To go back the other way, use chr. Give it sixty-five and you get capital A.
Race results can arrive as text. If you want to do maths with them, convert them to numbers. Use int to turn the text twelve into an integer. Use float to turn twelve point five into a real number. Use str to turn either number back into text.
Write Python code to join the first two letters of Bath to S T with one space between them. Check the slice first: it prints B A. Predict what you’d get if you joined the two parts directly. You’d get B A S T. Put a one-space string between them instead.