Shift a string
You're going to create a generator that, given a string, produces a sequence of constituent characters shifted by a specified number of positions shift
. For example, the string 'sushi'
produces the sequence 'h'
, 'i'
, 's'
, 'u'
, 's'
when we shift by 2 positions to the right (shift = 2
). When we shift by 2 positions to the left (shift = -2
), the resulting sequence will be 's'
, 'h'
, 'i'
, 's'
, 'u'
.
Tip: use the %
operator to cycle through the valid indices. Applying it to a positive or negative number gives a non-negative remainder, which can be helpful when shifting your index.
For example, consider the following variable string = 'python'
, holding a string of 6
characters:
2 % 6 = 2
(thus,string[2 % 6]
ist
)0 % 6 = 0
(thus,string[0 % 6]
isp
)-2 % 6 = 4
(thus,string[-2 % 6]
iso
)
This is a part of the course
“Practicing Coding Interview Questions in Python”
Exercise instructions
- Loop over the indices of a string using the provided
len_string
variable. - Find which character will correspond to the index when we perform the shift.
- Create a generator that shifts the string
'DataCamp'
by 3 positions to the right (i.e."ampDataC"
). - Create a new string using the generator and print it out.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
def shift_string(string, shift):
len_string = len(string)
# Loop over the indices of a string
for idx in ____:
# Find which character will correspond to the index.
____ ____[____]
# Create a generator
gen = ____
# Create a new string using the generator and print it out
string_shifted = ''.____
print(string_shifted)