Change each character in string to the next character in alphabet

前端 未结 8 1074
佛祖请我去吃肉
佛祖请我去吃肉 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:27

    This can be done much easier and efficiently by using a look-up instead of using index for each letter.

    look_up = dict(zip(string.ascii_lowercase, string.ascii_lowercase[1:]+'a'))
    

    The zip above creates tuples of the form ('a', 'b')... including ('z', 'a'). Feeding that into the dict constructor makes a dict of the same form.

    So now the code can be simply:

    def LetterChanges(s):
        from string import ascii_lowercase
        
        look_up = dict(zip(ascii_lowercase, ascii_lowercase[1:]+'a'))
        new_s = ''
        for letter in s:
            new_s += look_up[letter]
    
        return new_s
    

    Even this dict creation and the loop can be saved by using the str.maketrans method and feeding its result to str.translate:

    def LetterChanges(s):
        from string import ascii_lowercase
    
        return s.translate(str.maketrans(ascii_lowercase, ascii_lowercase[1:]+'a'))
    
    0 讨论(0)
  • 2021-01-03 16:31

    this is my code i think it is very simple

    def LetterChanges(st):
        index = 0
        new_word = ""
        alphapet = "abcdefghijklmnopqrstuvwxyzacd"
    
        for i in st.lower():
            if i.islower(): #check if i s letter
                index = alphapet.index(i) + 1 #get the index of the following letter
                new_word += alphapet[index]    
            else: #if not letter
                new_word += i    
        return new_word
    
    
    print LetterChanges(raw_input())
    
    0 讨论(0)
提交回复
热议问题