Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 8

Strings II: Indexing and Slicing

This lesson goes with Episode 8 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

8.1 Every character has a position

A string is a sequence, so each character has a place in the order. That place is called its index (the plural is indexes or indices). Here is the string "Python" with the index of each character written underneath:

  ┌───┬───┬───┬───┬───┬───┐
  │ P │ y │ t │ h │ o │ n │
  └───┴───┴───┴───┴───┴───┘
    0   1   2   3   4   5

To read one character, write the index in square brackets after the string:

word = "Python"
print(word[0])
print(word[1])
print(word[5])

Output

P
y
n

word[0] is read aloud as "word at zero" or "word sub zero". What you get back is itself a string, one character long. Python has no separate "character" type:

word = "Python"
print(type(word[0]))
print(len(word[0]))

Output

<class 'str'>
1

Why counting starts at zero

It feels strange at first. The best way to think about it: the index is not "which character", it is how far from the start. The first character is zero steps from the start. The second is one step away. A ruler works the same way: the first centimetre begins at the mark labelled 0.

Two facts follow from this, and they are worth memorising:

  • The first character is at index 0.
  • The last character is at index len(word) - 1. For a 6-character string, that is 5. There is no index 6.
word = "Python"
print(len(word))
print(word[len(word) - 1])

Output

6
n

The index can be any expression

Anything that works out to a whole number can go inside the brackets:

word = "Python"
position = 2
print(word[position])
print(word[position + 1])
print(word[len(word) // 2])

Output

t
h
h

The last line picks the character at the middle position: 6 // 2 is 3. Indexing also works directly on a literal, and on anything that gives a string:

print("Tokyo"[0])
print(str(2026)[3])

Output

T
6

str(2026) is "2026", and its character at index 3 is "6". That is how you pick a digit out of a number: convert it to text first.

Quick check

For city = "Lisbon", what are city[0], city[3] and city[len(city) - 1]?

Show the answer

Answer: "L", "b" and "n". The indexes of Lisbon run from 0 to 5.

Practice 8.1

Predict the output

What does it print?

word = "planet"
print(word[0])
print(word[3])
print(word[len(word) - 1])

Fill in the blank

Fill in the blank so that the program prints the first character of the word.

word = "Tokyo"
print(word[])

The finished program prints:

Target

T

Fix the bug

This should print the last digit of the whole number that the user types. It crashes. Fix it.

With the reply 4096, the program prints the lines below. Your program must print exactly these lines.

Example run

6

8.2 Counting from the end: negative indexes

Often you want the last character, or the one before it. Writing word[len(word) - 1] every time is clumsy, so Python lets you count from the end with negative indexes. -1 is the last character, -2 the one before, and so on:

  ┌───┬───┬───┬───┬───┬───┐
  │ P │ y │ t │ h │ o │ n │
  └───┴───┴───┴───┴───┴───┘
    0   1   2   3   4   5      counting from the front
   -6  -5  -4  -3  -2  -1      counting from the back
word = "Python"
print(word[-1])
print(word[-2])
print(word[-6])

Output

n
o
P

Every character therefore has two addresses. The rule connecting them: word[-k] is the same character as word[len(word) - k]. Python simply adds the length to a negative index for you.

Why does the back start at -1 and not -0? Because -0 is just 0, which already means the first character.

Practice 8.2

Predict the output

What does it print?

word = "garden"
print(word[-1])
print(word[-3])
print(word[-len(word)])

Multiple choice

For word = "silver", which of these is the same character as word[-2]?

Choose one answer

8.3 Going out of range: IndexError

Ask for a position that does not exist and Python stops with an IndexError:

word = "Python"
print(word[6])

Output

Traceback (most recent call last):
  File "index.py", line 2, in <module>
    print(word[6])
          ~~~~^^^
IndexError: string index out of range

Out of range means the index is outside the set of legal positions. For a string of length n:

Legal indexes For "Python" (length 6)
from 0 to n - 1 0, 1, 2, 3, 4, 5
from -n to -1 -6, -5, -4, -3, -2, -1

Anything else, such as 6, 10 or -7, is an error.

The empty string has no legal index at all. Even ""[0] is an IndexError, because there is no first character. This matters when the string comes from the user: if they press Enter without typing anything, reply[0] crashes.

The index must be a whole number

A position cannot be a decimal or a piece of text:

word = "Python"
print(word[1.0])

Output

Traceback (most recent call last):
  File "index.py", line 2, in <module>
    print(word[1.0])
          ~~~~^^^^^
TypeError: string indices must be integers, not 'float'

Even 1.0, which is a whole value, is refused because its type is float. This bites when the index comes from a division: len(word) / 2 is always a float (Chapter 4). Use // to get an int. It also bites when the index comes from input(), which gives text: convert it with int() first.

Quick check

Which of these are errors for s = "code"? s[4], s[-4], s[-5], s[2 / 2]

Show the answer

Answer: s[4] and s[-5] are IndexError (legal indexes are 0 to 3 and −4 to −1). s[2 / 2] is a TypeError, because 2 / 2 is the float 1.0. Only s[-4] works, and gives "c".

Practice 8.3

Multiple choice

What happens when this program runs?

word = "river"
print(word[5])
Choose one answer

Fix the bug

The user types a position counted the everyday way: 1 means the first letter and 6 means the last letter. The program should print that letter. Now it prints the wrong letter, and for 6 it crashes. Fix it.

With the reply 1, the program prints the lines below. Your program must print exactly these lines.

Example run

b

8.4 Slicing: taking a piece

Indexing gives one character. Slicing gives a whole section. Write two indexes separated by a colon:

word = "Python"
print(word[0:2])
print(word[2:6])
print(word[1:4])

Output

Py
thon
yth

The form is word[start:stop], and the rule is:

The slice begins at start and goes up to, but does not include, stop.

So word[1:4] is the characters at indexes 1, 2 and 3. Index 4 is where it stops, and that character is left out.

The fence-post picture

"Up to but not including" is easier to get right with a different picture. Stop thinking of indexes as pointing at the characters. Think of them as pointing at the gaps between the characters, like the posts of a fence, with the characters as the panels between the posts:

  ┌───┬───┬───┬───┬───┬───┐
  │ P │ y │ t │ h │ o │ n │
  └───┴───┴───┴───┴───┴───┘
  0   1   2   3   4   5   6

A slice is a cut at two posts. word[1:4] cuts at post 1 and post 4 and gives you everything in between: y, t, h. With this picture there is nothing to remember about including or excluding. You get what lies between the two cuts.

The picture also explains why 6 is allowed as a stop for "Python", although word[6] is an error: there is a post 6, at the very end, but there is no panel after it.

Why stop is left out

This design looks odd, but it gives three properties that make slices pleasant to work with:

word = "Python"
print(len(word[1:4]))        # 1. the length is stop - start
print(word[0:2] + word[2:6]) # 2. pieces that share a boundary fit together
print(word[0:3])             # 3. [0:n] is "the first n characters"

Output

3
Python
Pyt
  1. The length of a slice is stop - start: 4 − 1 is 3.
  2. word[0:2] and word[2:6] share the number 2, and together they give the whole string with no overlap and no gap.
  3. word[0:n] is exactly the first n characters.

If stop were included, all three would need a "plus one" or "minus one" somewhere, and that is where bugs live.

Quick check

For s = "notebook", what are s[0:4], s[4:8] and s[2:5]? How long is s[3:7]?

Show the answer

Answer: "note", "book" and "teb". s[3:7] has length 7 − 3, which is 4 (it is "eboo").

Practice 8.4

Predict the output

What does it print?

s = "sunflower"
print(s[0:3])
print(s[3:9])
print(len(s[2:7]))

Fill in the blank

Fill in the two numbers, both counted from the front, so that the program prints the last four letters of the word.

word = "football"
print(word[:])

The finished program prints:

Target

ball

8.5 Leaving numbers out

Both numbers in a slice are optional. Leave out start and the slice begins at the beginning. Leave out stop and it runs to the end:

word = "Python"
print(word[:2])    # from the beginning up to post 2
print(word[2:])    # from post 2 to the end
print(word[:])     # everything

Output

Py
thon
Python

Read word[:2] as "the first two characters" and word[2:] as "everything except the first two". These two forms are what you will write most of the time.

For any string and any number n, the two halves always fit back together:

word = "Python"
n = 4
print(word[:n] + word[n:])
print(word[:n] + word[n:] == word)

Output

Python
True

You can think of word[:n] and word[n:] as cutting the string in two at post n.

Practice 8.5

Put the lines in order

Put the lines in order. The program asks for a text, drops its first two characters, keeps the first three characters of what is left, and prints them.

With the reply keyboard, the program in the right order prints:

Target

ybo
  1. text = input("Text: ")
  2. short = rest[:3]
  3. print(short)
  4. rest = text[2:]

8.6 Negative numbers in slices

Negative indexes work in slices exactly as they do in indexing: they count posts from the end.

  ┌───┬───┬───┬───┬───┬───┐
  │ P │ y │ t │ h │ o │ n │
  └───┴───┴───┴───┴───┴───┘
  0   1   2   3   4   5   6
 -6  -5  -4  -3  -2  -1
word = "Python"
print(word[-3:])     # the last three characters
print(word[:-1])     # everything except the last character
print(word[1:-1])    # everything except the first and the last
print(word[-4:-2])   # between post -4 and post -2

Output

hon
Pytho
ytho
th

Two of these are worth learning by heart:

  • word[-n:] is the last n characters.
  • word[:-n] is everything except the last n.

They are the mirror images of word[:n] and word[n:].

Practice 8.6

Fill in the blank

Fill in the blank with a negative number and a colon, so that the program prints the last three characters of the file name.

name = "picture.png"
print(name[])

The finished program prints:

Target

png

Predict the output

What does it print?

s = "sandwich"
print(s[-4:])
print(s[:-4])
print(s[1:-1])

Write code

Name and ending. Ask for a file name that ends with a dot and three letters, such as photo.png. Print two lines: first the file name without its last four characters, then only its last three characters.

With the reply photo.png, the program prints the lines below. Your program must print exactly these lines.

Example run

photo
png

8.7 Slices never raise an error

Indexing is strict: a bad index is an IndexError. Slicing is forgiving. If a slice asks for more than exists, Python quietly gives whatever is there:

word = "Python"
print(word[2:100])
print(word[-100:3])
print(repr(word[10:20]))
print(repr(word[4:2]))

Output

thon
Pyt
''
''
  • word[2:100]: there is no post 100, so the slice stops at the end.
  • word[-100:3]: there is no post −100, so the slice starts at the beginning.
  • word[10:20]: both cuts are past the end, and nothing lies between them. The result is the empty string.
  • word[4:2]: start is after stop, so again nothing is in between.
Indexing s[i] Slicing s[i:j]
Gives back one character a string of any length, possibly empty
Out of range IndexError no error; the slice is trimmed to fit
On an empty string always an error always ""

This makes slicing the safe way to look at the start of a string that might be empty. reply[0] crashes on an empty reply; reply[:1] gives "".

reply = ""
print(repr(reply[:1]))

Output

''

Practice 8.7

Multiple choice

For s = "tea", three of these give a string. Which one stops with an error?

Choose one answer

Predict the output

What does it print?

s = "lamp"
print(len(s[2:50]))
print(repr(s[9:]))
print(s[-50:2])

Fix the bug

This program shows the first character of the reply. It crashes when the user presses Enter without typing anything. Fix it so that an empty reply gives an empty string.

With the reply , the program prints the lines below. Your program must print exactly these lines.

Example run

''

8.8 The third number: step

A slice can take a third number, the step: word[start:stop:step]. It says how far to jump each time. The default is 1, meaning every character.

digits = "0123456789"
print(digits[::2])      # every second character, from the start
print(digits[1::2])     # every second character, starting at index 1
print(digits[::3])      # every third character
print(digits[2:9:3])    # start at 2, stop before 9, jump 3

Output

02468
13579
0369
258

For digits[2:9:3], Python takes index 2, then 5, then 8. The next would be 11, which is past the stop, so it ends there.

Going backwards

A negative step walks from right to left. The most famous slice in Python reverses a string:

word = "Python"
print(word[::-1])

Output

nohtyP

With a negative step, the defaults flip: a missing start means the end of the string, and a missing stop means "go all the way past the beginning". So [::-1] starts at the last character and steps back one at a time until it runs out.

When you give explicit numbers with a negative step, start must be to the right of stop, and stop is still left out:

word = "Python"
print(word[4:1:-1])     # indexes 4, 3, 2
print(word[::-2])       # indexes 5, 3, 1
print(repr(word[1:4:-1]))   # going left from 1 never reaches 4

Output

oht
nhy
''

A step of zero would never move, so it is not allowed: word[::0] raises ValueError: slice step cannot be zero.

Quick check

For s = "abcdefg", what are s[::3], s[::-1] and s[1:6:2]?

Show the answer

Answer: "adg" (indexes 0, 3, 6), "gfedcba", and "bdf" (indexes 1, 3, 5).

Practice 8.8

Predict the output

What does it print?

letters = "bcdfghjk"
print(letters[::2])
print(letters[1::3])
print(letters[::-1])

Fill in the blank

Fill in the blank so that the program prints the word reversed.

word = "drawer"
print(word[])

The finished program prints:

Target

reward

Multiple choice

What happens when this program runs?

word = "stone"
print(word[::0])
Choose one answer

Put the lines in order

Put the lines in order. The program asks for a word, cuts out the characters at indexes 1 to 3, reverses that piece, and prints it.

With the reply garden, the program in the right order prints:

Target

dra
  1. piece = word[1:4]
  2. word = input("Word: ")
  3. flipped = piece[::-1]
  4. print(flipped)

8.9 You cannot change a character

Chapter 7 said strings are immutable. Here is the proof. Square brackets can read a character, but they cannot write one:

word = "Python"
word[0] = "J"

Output

Traceback (most recent call last):
  File "change.py", line 2, in <module>
    word[0] = "J"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

Item assignment means "putting a new value at an index". Strings do not allow it, and they do not allow deleting a character with del word[0] either.

The way to "change" a string is always the same: build a new string from pieces of the old one. Slices give you the pieces and + joins them:

word = "Python"
new_word = "J" + word[1:]
print(new_word)
print(word)

Output

Jython
Python

word[1:] is everything except the first character. Put a J in front, and you have a new string. The original is untouched, as the second print shows. If you no longer need the old one, reuse the name: word = "J" + word[1:].

The same idea handles a change anywhere. To replace the character at position i, take everything before it, the new character, and everything after it:

word = "Python"
i = 3
print(word[:i] + "H" + word[i + 1:])

Output

PytHon
   word[:3]     new     word[4:]
  ┌───┬───┬───┐ ┌───┐ ┌───┬───┐
  │ P │ y │ t │ │ H │ │ o │ n │
  └───┴───┴───┘ └───┘ └───┴───┘

The same pattern inserts (use word[i:] for the second piece, so nothing is skipped) and deletes (leave out the middle piece):

word = "Python"
print(word[:2] + "---" + word[2:])   # insert at post 2
print(word[:2] + word[3:])           # delete the character at index 2

Output

Py---thon
Pyhon

Why are strings immutable?

It can feel like a restriction, but it is a deliberate gift. Because a string can never change, you can hand it to any part of a program and be certain it will come back the same. Two names can safely share one string. And strings can be used as keys for fast lookup in dictionaries → Chapter 31. When you do need a sequence of characters that you can edit in place, you use a list → Chapter 25.

Practice 8.9

Multiple choice

The error message for word[0] = "J" talks about item assignment. What does that mean?

Choose one answer

Fix the bug

This should print the word with the character at index 2 replaced by a dash. Now the old character is still there, and the result is one character too long. Fix it.

With the reply river, the program prints the lines below. Your program must print exactly these lines.

Example run

ri-er

Write code

Delete one character. Ask for a word first, then for a position (a whole number, counted from 0). Print one line: the word without the character at that position.

With the replies planet then 0, the program prints the lines below. Your program must print exactly these lines.

Example run

lanet

8.10 Everyday recipes

These patterns come up constantly. Each one is just an index or a slice.

text = "programming"
print(text[0])             # first character
print(text[-1])            # last character
print(text[:3])            # first three
print(text[-3:])           # last three
print(text[1:])            # all but the first
print(text[:-1])           # all but the last
print(text[1:-1])          # without the first and the last
print(text[len(text) // 2])   # the middle character
print(text[::-1])          # reversed
print(text[::2])           # every other character

Output

p
g
pro
ing
rogramming
programmin
rogrammin
a
gnimmargorp
pormig
You want Write
First character s[0] (or s[:1] if s might be empty)
Last character s[-1] (or s[-1:] if s might be empty)
First n characters s[:n]
Last n characters s[-n:]
Without the first n s[n:]
Without the last n s[:-n]
Reversed s[::-1]
A copy with character i replaced s[:i] + new + s[i + 1:]

Three small programs

Is it a palindrome? A palindrome reads the same in both directions, like level. Compare the string with its reverse:

word = "level"
print(word == word[::-1])
word = "lever"
print(word == word[::-1])

Output

True
False

Hide a card number. Show only the last four digits and replace the rest with stars:

card = "4929123456781234"
hidden = "*" * (len(card) - 4) + card[-4:]
print(hidden)

Output

************1234

Rotate a string. Move the first n characters to the end, like passengers moving along a bench:

text = "abcdef"
n = 2
print(text[n:] + text[:n])

Output

cdefab

Cut at post n, then join the two halves in the opposite order.

Practice 8.10

Fill in the blank

Fill in the blank so that only the last four characters of the code stay visible after the stars.

code = "731955204486"
hidden = "*" * (len(code) - 4) + code[]
print(hidden)

The finished program prints:

Target

********4486

Write code

Rotate to the left. Ask for a text first, then for a whole number n. Print one line: the text with its first n characters moved to the end.

With the replies bcdefg then 2, the program prints the lines below. Your program must print exactly these lines.

Example run

defgbc

8.11 Common mistakes

The mistake What you see The fix
Using s[1] for the first character The second character The first is s[0]
Using s[len(s)] for the last character IndexError: string index out of range s[-1] or s[len(s) - 1]
Expecting s[2:5] to include index 5 One character fewer than expected stop is left out; write s[2:6]
An index from division: s[len(s) / 2] TypeError: string indices must be integers Use //
An index from input() TypeError: string indices must be integers, not 'str' Convert with int()
s[0] = "X" TypeError: 'str' object does not support item assignment s = "X" + s[1:]
Round brackets: s(0) TypeError: 'str' object is not callable Indexing uses square brackets
Indexing a reply that may be empty IndexError when the user just presses Enter Use a slice, reply[:1], or check first
s[5:2] hoping for a reversed piece '' A backwards slice needs a negative step: s[5:2:-1]
A comma instead of a colon: s[1,3] TypeError: string indices must be integers, not 'tuple' s[1:3]

8.12 Putting it together

Practice 8.12

Put the lines in order

Put the lines in order. The program asks for a booking code such as TYO-20261123-0457-B, takes the year out of it, and prints the year that follows.

With the reply TYO-20261123-0457-B, the program in the right order prints:

Target

2027
  1. year = int(code[4:8])
  2. next_year = year + 1
  3. code = input("Booking code: ")
  4. print(next_year)

8.13 How indexing and slicing work

+ Practice

Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.

Questions

Check yourself

What is the index of the first character of a string? Of the last character of a string with 10 characters?

Show the answer

0. For 10 characters, the last index is 9.

Check yourself

Give two different ways to get the last character of name.

Show the answer

name[-1] and name[len(name) - 1].

Check yourself

Why is "Python"[6] an error although the string has 6 characters?

Show the answer

The six characters have indexes 0 to 5. Index 6 would be a seventh character, which does not exist.

Check yourself

What does s[2:5] give for s = "abcdefgh"? Which index is not included?

Show the answer

"cde": indexes 2, 3 and 4. Index 5 ("f") is not included.

Check yourself

In the fence-post picture, how many posts does a string of length 5 have?

Show the answer

Six: posts 0 to 5. There is always one more post than there are characters.

Check yourself

What do s[:4] and s[4:] have in common with the whole string s?

Show the answer

Joined together they give back s exactly: s[:4] + s[4:] == s.

Check yourself

What is the difference between s[10] and s[10:] when s has only 5 characters?

Show the answer

s[10] is an IndexError. s[10:] is the empty string, because slices are trimmed instead of raising.

Check yourself

What does the step in s[::3] do? What does s[::-1] do?

Show the answer

s[::3] takes every third character, starting at index 0. s[::-1] walks backwards one step at a time, giving the reversed string.

Check yourself

Why does s[0] = "X" fail? Write the correct way to get a new string with the first character replaced.

Show the answer

Strings are immutable, so a character cannot be assigned. Build a new string: s = "X" + s[1:].

Check yourself

Why must you write s[len(s) // 2] and not s[len(s) / 2]?

Show the answer

/ always gives a float, and an index must be an int. // gives an int.

Predict the output

Predict the output

s = "keyboard"
print(s[0], s[3], s[-1], s[-3])
print(s[len(s) - 2])

Predict the output

s = "keyboard"
print(s[:3], s[3:], s[2:6])
print(s[-5:], s[:-5], s[-5:-2])

Predict the output

s = "0123456789"
print(s[::4], s[1::4], s[::-3])
print(s[8:2:-2], s[2:8][::-1])

Predict the output

s = "data"
print(repr(s[4:]), repr(s[2:2]), repr(s[3:1]), repr(s[-99:1]))
print(len(s[1:100]))

Predict the output

s = "hello"
t = s[:1] + "a" + s[2:]
print(s, t)
print(t[::-1][0] + t[0])

Fix the bug

Fix the bug

This should print the last letter of the word. It crashes.

The program prints the lines below. Your program must print exactly these lines.

Example run

w

Fix the bug

This should print the first three letters, win. It prints wi.

The program prints the lines below. Your program must print exactly these lines.

Example run

win

Fix the bug

This should print the middle character of a word with an odd number of letters. It crashes.

The program prints the lines below. Your program must print exactly these lines.

Example run

p

Fix the bug

This should turn "cat" into "hat". It crashes.

The program prints the lines below. Your program must print exactly these lines.

Example run

hat

Fix the bug

This should print the letter at the position the user asks for. It crashes.

With the reply 2, the program prints the lines below. Your program must print exactly these lines.

Example run

a

Coding problems

Write code · Easy

Initials. Store a first name and a last name, and print the two initials with dots, such as M.T.

Use the first name Maya and the last name Tanaka. Print one line: the two initials, each followed by a dot, with no spaces.

The program prints the lines below. Your program must print exactly these lines.

Example run

M.T.

Write code · Easy

First and last. Ask for a word and print its first character, its last character, and the word without those two.

Print three lines: the first character, then the last character, then the word without those two.

With the reply string, the program prints the lines below. Your program must print exactly these lines.

Example run

s
g
trin

Write code · Easy

Last four. Ask for a phone number as text and print only its last four characters.

Print one line with only the last four characters. If the reply is shorter than four characters, print all of it.

With the reply 5550142907, the program prints the lines below. Your program must print exactly these lines.

Example run

2907

Write code · Medium

Swap the halves. Ask for a word and print it with its two halves swapped: notebook becomes booknote. For a word with an odd length, the first half is the shorter one.

Print one line: the second half followed by the first half.

With the reply notebook, the program prints the lines below. Your program must print exactly these lines.

Example run

booknote

Write code · Medium

Palindrome test. Ask for a word and print True if it reads the same forwards and backwards.

Print one line: True or False.

With the reply racecar, the program prints the lines below. Your program must print exactly these lines.

Example run

True

Write code · Medium

Capital in the middle. Given word = "python" and an index i, print the word with the character at i replaced by "*". Test with i = 0, i = 3 and i = 5.

Print three lines: the result for i = 0, then for i = 3, then for i = 5.

The program prints the lines below. Your program must print exactly these lines.

Example run

*ython
pyt*on
pytho*

Write code · Hard

Date untangler. A date is stored as the text "2026-11-23". Using slices and int(), print it in the form 23.11.2026, and then print how many days are left in that month, assuming it has 30 days.

Print two lines: the date with dots, then Days left: followed by one space and the number.

The program prints the lines below. Your program must print exactly these lines.

Example run

23.11.2026
Days left: 7

Write code · Hard

Pick and mix. Take two strings such as "abcd" and "1234". Using only slices with a step and +, build a new string from the characters at even indexes of the first string followed by the characters at odd indexes of the second ("ac24"). Print it, and then print its reverse.

Use the two strings from the example. Print the new string first, then its reverse on a second line.

The program prints the lines below. Your program must print exactly these lines.

Example run

ac24
42ca

Write code · Hard

Mirror. Ask for a word and print a mirrored version in which the last letter is not doubled: abc becomes abcba.

Print one line: the word followed by its mirror image, with the last letter written only once.

With the reply level, the program prints the lines below. Your program must print exactly these lines.

Example run

levelevel

Chapter project: Library card

Project

Make a library card. A library builds a short card code from the details of each new member. Write a program that asks three questions, in this order:

  1. the first name
  2. the last name (it has three letters or more)
  3. the date of joining, always typed in the form 2026-03-09 (year, month, day)

Then print four lines, with exactly these labels and one space after each colon:

  • Code: then the card code. The card code is the first three characters of the last name, then the first character of the first name, then the last two digits of the year.
  • Joined: then the date in the form day/month/year. The day and the month are shown as numbers, so a zero at the front disappears.
  • Check: then the card code reversed.
  • Hidden: then the first character of the last name, followed by one star for every other character of the last name.

Count posts before you write the slices, as section 8.12 did, and store the card code in a variable so that you can use it two times.

With the replies Maya then Tanaka then 2026-03-09, the program prints the lines below. Your program must print exactly these lines.

Example run

Code: TanM26
Joined: 9/3/2026
Check: 62MnaT
Hidden: T*****