Based on a user inputted string, how would you rotate the string based on a specific group of letters and symbols. The user would also input the rotation amount. For example, if the user inputs a rotation of 3, the individual characters that the user already inputted are rotated 3 characters down the group/list of characters.
Asked
Active
Viewed 450 times
-1
-
1Please include more specific detials like some sample input and expected output plus what you have tried so far and were you got stuck. – Tanveer Alam Nov 21 '14 at 00:07
-
check this http://stackoverflow.com/questions/4528740/wrapping-around-a-python-list-as-a-slice-operation – user3885927 Nov 21 '14 at 00:10
2 Answers
1
Here's a cool way
rotated = ''.join([mystring[i-offset] for i in range(len(mystring))])
It can overflow (get an out of bounds error) if the offset is too high, which you'll have to account for if relevant
Explanation:
we index into the string and subtract by offset, making use of the fact that negative indexing wraps in Python (though only once, hence the possible overflow). List comprehension allows us to do this for every character in one line, and the join function let's us push these back together into one string

en_Knight
- 5,301
- 2
- 26
- 46
0
def rotate_left(string, offset):
return string[offset:] + string[:offset]
def rotate_right(string, offset):
return string[-offset:] + string[:-offset]
>>> rotate_left('hello world', 3)
'lo worldhel'
>>> rotate_right('hello world', 3)
'rldhello wo'

Kevin Markham
- 5,778
- 1
- 28
- 36