打印在Python中使用n前进的字母

时间:2015-05-10 17:56:30

标签: python string

我怎么能写一个python程序来输入一些字母并在输出中打印出来(字母+ n)。示例

my_string = 'abc'
expected_output = 'cde' # n=2

我认为的一种方法是使用str.maketrans,并将原始输入映射到(字母+ n)。还有其他办法吗?

PS:xyz应转换为abc

我也试图编写自己的代码,(除了提到的无限更好的答案):

number = 2
prim =  """abc! fgdf """
final = prim.lower()
for x in final:
    if(x =="y"):
        print("a", end="")
    elif(x=="z"):
        print("b", end="")
    else:
        conv = ord(x)
        x = conv+number
        print(chr(x),end="")

有关如何转换特殊字符的任何评论?感谢

4 个答案:

答案 0 :(得分:2)

这样的东西
>>> my_string = "abc"
>>> n = 2
>>> "".join([ chr(ord(i) + n) for i in my_string])
'cde'

注意正如评论中所提到的,当遇到像xyz

这样的边缘情况时该问题有点模糊

<小时/> 修改要处理边缘情况,您可以编写类似

的内容
>>> from string import ascii_lowercase
>>> lower = ascii_lowercase
>>> input = "xyz"
>>> "".join([ lower[(lower.index(i)+2)%26] for i in input ])
'zab'
>>> input = "abc"
>>> "".join([ lower[(lower.index(i)+2)%26] for i in input ])
'cde'

答案 1 :(得分:2)

如果你不关心环绕,你可以这样做:

def shiftString(string, number):
    return "".join(map(lambda x: chr(ord(x)+number),string))

如果你想环绕(想想Caesar chiffre),你需要指定字母表开始和结束的起点和终点:

def shiftString(string, number, start=97, num_of_symbols=26):
    return "".join(map(lambda x: chr(((ord(x)+number-start) %
           num_of_symbols)+start) if start <= ord(x) <= start+num_of_symbols
           else x,string))

例如,如果将abcxyz转换为cdezab,则可以转换为public class ReadabilitySettings { public ReadabilitySettings() { } private bool _reababilityEnabled; public bool ReadabilityEnabled { get { return _reababilityEnabled; } set { _reababilityEnabled = value; } } private string _fontName; public string FontName { get { return _fontName; } set { _fontName = value; } } private bool _isInverted; public bool IsInverted { get { return _isInverted; } set { _isInverted = value; } } public enum FontSizes { Small = 0, Medium = 1, Large = 2 } private FontSizes _fontSize; public FontSizes FontSize { get { return _fontSize; } set { _fontSize = value; } } } }

如果您确实想将其用于“加密”,请务必从中排除非字母字符(如空格等)。

编辑:我的Vignère tool in Python

的无耻插件

edit2:现在只在其范围内转换。

答案 2 :(得分:0)

我对代码进行了以下更改:

number = 2
prim =  """Special() ops() chars!!"""
final = prim.lower()
for x in final:
    if(x =="y"):
        print("a", end="")
    elif(x=="z"):
        print("b", end="")
    elif (ord(x) in range(97, 124)):
        conv = ord(x)
        x = conv+number
        print(chr(x),end="")
    else:
        print(x, end="")

**Output**: urgekcn() qru() ejctu!!

答案 3 :(得分:0)

test_data = (('abz', 2), ('abc', 3), ('aek', 26), ('abcd', 25))
# translate every character
def shiftstr(s, k):
    if not (isinstance(s, str) and isinstance(k, int) and k >=0):
        return s
    a = ord('a')
    return ''.join([chr(a+((ord(c)-a+k)%26)) for c in s])

for s, k in test_data:
    print(shiftstr(s, k))
print('----')

# translate at most 26 characters, rest look up dictionary at O(1)
def shiftstr(s, k):
    if not (isinstance(s, str) and isinstance(k, int) and k >=0):
        return s
    a = ord('a')
    d = {}
    l = []
    for c in s:
        v = d.get(c)
        if v is None:
            v = chr(a+((ord(c)-a+k)%26))
            d[c] = v
        l.append(v)
    return ''.join(l)

for s, k in test_data:
    print(shiftstr(s, k))
 Testing shiftstr_test.py (above code):
 $ python3 shiftstr_test.py 
 cdb
 def
 aek
 zabc
----
cdb
def
aek
zabc

It covers wrapping.