Python: How to move forward or backward together in String printable
本问题已经有最佳答案,请猛点这里访问。
如何在
例如:
1 | >> chars ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" |
然后输出为:
1 | 123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0 |
号
1 2 3 4 5 6 7 | >>> chars[2:] + chars[:2] '23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01' >>> >>> >>> chars[-2:] + chars[:-2] 'YZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX' >>> |
号
甚至可以用字符串、步骤和方向作为参数为其定义函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | >>> 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 |
另一种方法是使用具有
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> 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 | result = chars[1:] + chars[:1] |