Letters by position
Pick letters out of a word by their position, and join pieces together. About 9 minutes.
A row of letters
A piece of text, which programmers call a string, is a row of letters in numbered boxes. Spaces and punctuation get a box too. You find a letter by its position, and here is the surprise: the first letter is at position 0, not 1.
So in the word "plane" the p is at position 0, the l at 1, and the e at 4. The last letter is always at the position one less than the length of the word.
word = "plane" first = word[0] # "p" last = word[4] # "e"
- first
- p
The letter at position 0 is the first letter. It is p.
Cutting and joining
You can cut a piece off a string, and you can glue pieces together with a plus sign. Joining strings is called concatenation, which is a long name for a simple idea.
To move the first letter to the end of a word, do three things. Pick out the first letter. Cut off everything after it. Then glue the rest first and the first letter second. Each language has its own way of cutting. Your editor shows the one for your language.
word = "plane" first = word[0] rest = word[1:] # "lane" new_word = rest + first
word is "plane". Positions start at 0. Which letter is at position 2?
- Aa
- Bl
- Cn
Show the answer
a. p is at 0, l is at 1, and a is at 2.
Rotate by one
Move the first letter of a word to the end, and return the new word. For example "hello" becomes "elloh". A word with fewer than two letters stays as it is.
s = "hello" → "elloh"
0 ≤ length of s ≤ 1,000 · lowercase letters only