Change each character in string to the next character in alphabet

前端 未结 8 1075
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 15:45

I am coding in Python 2.7 using PyCharm on Ubuntu.

I am trying to create a function that will take a string and change each character to the character that would be

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 16:22

    I think you are making this too complicated.

    Just use modulo to roll around to the beginning of the string:

    from string import ascii_letters
    
    s='abcxyz ABCXYZ'
    ns=''
    for c in s:
        if c in ascii_letters:
            ns=ns+ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)]
        else:
            ns+=c
    

    Which you can reduce to a single unreadable line if you wish:

    ''.join([ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)] 
                 if c in ascii_letters else c for c in s])
    

    Either case,

    Turns      abcxyz ABCXYZ
    into       bcdyzA BCDYZa
    

    If you want it to be limited to upper of lower case letters, just change the import:

    from string import ascii_lowercase as letters
    
    s='abcxyz'
    ns=''
    for c in s:
        if c in letters:
            ns=ns+letters[(letters.index(c)+1)%len(letters)]
        else:
            ns+=c
    

提交回复
热议问题