0

How to shift forward or backward in string.printable whithout string.maketrans?

for example:

>> chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

and then output is:

123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
agaust
  • 97
  • 3
  • 19

2 Answers2

1
>>> chars[2:] + chars[:2]
'23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01'
>>> 
>>> 
>>> chars[-2:] + chars[:-2]
'YZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX'
>>> 

You can even define a function for that, with your string, the steps and direction as parameters:

>>> def shift(s, step, side='Right'):
        step %= len(s) #Will generate correct steps even step > len(s)
        if side == 'Right':
            return s[-step:]+s[:-step]
        elif side == 'Left':
            return s[step:]+s[:step]
        else:
            print 'Please, Specify either Right or Left shift'
            return -1 #as exit code


>>> shift(chars, 2, 'Right')
'YZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX'
>>> shift(chars, 2, 'Left')
'23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01'
>>> f(chars, 2, 'No_Direction')
Please, Specify either Right or Left shift
-1

Another way is to use deque class of the collections module, which has rotate method, this way:

>>> from collections import deque
>>> 
>>> d = deque(chars)
>>> d
deque(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'])
>>> 
>>> d.rotate(1)
>>> d
deque(['Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'])
>>> d.rotate(-1)
>>> d
deque(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'])
>>> d.rotate(3)
>>> ''.join(list(d))
'XYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW'
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
0

You can get that by slicing after the last character index you'd like to shift, 1 in this case:

result = chars[1:] + chars[:1]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97