Python:如何在字符串可打印中一起向前或向后移动

时间:2016-01-01 11:25:19

标签: python

如何在string.printable string.maketrans之前向前或向后移动?{/ p>

例如:

>> chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

然后输出是:

123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0

2 个答案:

答案 0 :(得分:1)

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

你甚至可以为它定义一个函数,用你的字符串,步骤和方向作为参数:

>>> 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

另一种方法是使用具有collections方法的rotate模块的deque类,这样:

>>> 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'

答案 1 :(得分:0)

你可以通过切换你要转移的最后一个字符索引来获得,1在这种情况下:

result = chars[1:] + chars[:1]