Menu

String Manipulation

String slicing

A substring is a part of a string. Slicing extracts a substring using square brackets with a start position and an end position separated by a colon, such as [2:5].

The character at the start position is included, but the character at the end position is not. In the string kangaroo, position 2 is n and position 5 is r. The slice kangaroo[2:5] takes positions 2, 3 and 4, giving nga. Position 5 is only the stopping point, so no character from it is included.

How many characters a slice contains

The number of characters in a slice is the end position minus the start position: 5 โˆ’ 2 = 3 characters. To take a known number of characters from a given start, add the number you need to the start to find the end. Starting at 4 and taking 3 characters uses [4:7], because 4 + 3 = 7.

Leaving positions out

  • Omit the start and slicing begins at position 0. So [:3] gives the first 3 characters.
  • Omit the end and the slice runs to the end of the string. So [4:] starts at position 4 and keeps every character after it.
  • For the last few characters whatever the length, start at the string length minus the number required and leave out the end. For the last 4 characters of a string stored in word, use word[len(word) - 4:].

A slice of length one can pick out the same single character as indexing. word[3:4] contains one character, just like word[3].

word = input("Enter a word: ")
print(word[1:4])
print(word[:2])
print(word[len(word) - 3:])

Output when the user types sprinkler:

Enter a word: sprinkler
pri
sp
ler

Building route codes

Slices are useful when a code or label must be made from parts of existing strings. Take each slice, change its case if needed, then join the pieces with +. For example, the first two letters of Norwich and the last four letters of Manchester can become no + ster, making the route code noster.

departure = input("Departure station: ")
arrival = input("Arrival station: ")
departure_part = departure[:2].lower()
arrival_part = arrival[len(arrival) - 4:].lower()
route_code = departure_part + arrival_part
print(route_code)

Output when the user types Norwich, Manchester:

Departure station: Norwich
Arrival station: Manchester
noster

Practise this