Last updated: Apr 10, 2024
Reading timeยท2 min
Use string slicing to print the alternate characters in a string, e.g.
print(string[::2])
.
The slice will contain every other character of the original string.
my_str = 'bobbyhadz' result = my_str[::2] print(result) # ๐๏ธ bbyaz result = my_str[1::2] print(result) # ๐๏ธ obhd
We used string slicing to print the alternate characters in a string.
The syntax for string slicing
is my_str[start:stop:step]
.
The start
index is inclusive, whereas the stop
index is exclusive (up to,
but not including).
0
, and the last character has an index of -1
or len(my_str) - 1
.The slice my_str[::2]
starts at index 0
and goes to the end of the string
selecting every second character.
my_str = 'bobbyhadz' result = my_str[::2] print(result) # ๐๏ธ bbyaz result = my_str[1::2] print(result) # ๐๏ธ obhd
The slice my_str[1::2]
starts at index 1
and goes to the end of the string
selecting every second character.
A more manual approach would be to use the enumerate()
function to get access
to the index of the current iteration.
my_str = 'bobbyhadz' result = '' for index, char in enumerate(my_str): if index % 2 == 0: result += char print(result) # ๐๏ธ bbyaz
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
for index, char in enumerate('abc'): print(index, char) # ๐๏ธ 0 a, 1 b, 2 c
On each iteration, we use the modulo %
operator to check if the remainder of
dividing the index by 2
equals 0
.
The modulo (%) operator returns the remainder from the division of the first value by the second.
print(10 % 2) # ๐๏ธ 0 print(10 % 4) # ๐๏ธ 2
If the index is an even number, we add the character to a new string.
my_str = 'bobbyhadz' result = '' for index, char in enumerate(my_str): if index % 2 == 0: result += char print(result) # ๐๏ธ bbyaz
The +=
operator is a shorthand for result = result + char
.
Which approach you pick is a matter of personal preference. I'd go with using string slicing as it is quite readable and more concise.
You can learn more about the related topics by checking out the following tutorials: