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)
This exercise is part of the course
Practicing Coding Interview Questions in Python
Prepare for your next coding interviews in Python.
This chapter focuses on iterable objects. We'll refresh the definition of iterable objects and explain, how to identify one. Next, we'll cover list comprehensions, which is a very special feature of Python programming language to define lists. Then, we'll recall how to combine several iterable objects into one. Finally, we'll cover how to create custom iterable objects using generators.
Exercise 1: What are iterable objects?Exercise 2: enumerate()Exercise 3: IteratorsExercise 4: Traversing a DataFrameExercise 5: What is a list comprehension?Exercise 6: Basic list comprehensionsExercise 7: Prime number sequenceExercise 8: Coprime number sequenceExercise 9: What is a zip object?Exercise 10: Combining iterable objectsExercise 11: Extracting tuplesExercise 12: Creating a DataFrameExercise 13: What is a generator and how to create one?Exercise 14: Shift a stringExercise 15: Throw a diceExercise 16: Generator comprehensionsWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.