【问题标题】:Python code for string modification doesn't work properly用于字符串修改的 Python 代码无法正常工作
【发布时间】:2018-04-04 17:22:55
【问题描述】:

这段代码应该接受一个字符串输入并输出另一个字符串,它只是输入字符串的修改版本。但我无法让它工作。

它应该输出一个字符串,其中每个字母都是输入字符串的下一个字母。但是在运行代码时,它只是输出相同的输入字符串而不是修改后的字符串。

def str_changer(string):

       string_list = list(string)
       alphabets = 'abcdefghijklmnopqrstuvwxyz'
       positions = []
       for letter in string_list:
         positions.append(alphabets.index(letter))
       for each in positions:
         each = each + 1
       for each in string_list:
         string_list[string_list.index(each)] = 
       alphabets[positions[string_list.index(each)]]

       another = ''.join(string_list)



       return another



    lmao = raw_input('Enter somin\'')
    print str_changer(lmao)

【问题讨论】:

  • string_list[string_list.index(each)] = 你错过了这一行的结尾吗?
  • @DavyM 我想他们已经用下一行包裹了它,所以string_list[string_list.index(each)] = alphabets[positions[string_list.index(each)]]
  • 你可以使用from string import ascii_lowercase,而不是写出字母表,它会给你'abcdefghijklmnopqrstuvwxyz'
  • each = each +1 似乎有问题,不太可能产生太大影响。

标签: python string python-2.7


【解决方案1】:

您只需 1 行即可完成:

s = 'abcdz'
print(''.join(chr(ord(letter) + 1) if letter != 'z' else 'a' for letter in s))
# bcdea

演示

>>> ord('a')
97
>>> ord('b')
98
>>> chr(ord('a') + 1)
'b'

【讨论】:

    【解决方案2】:

    这应该适合你。您应该使用% 来说明z

    重点是您不需要显式构建职位列表。

    def str_changer(string):
    
        string_list = list(string)
        alphabets = 'abcdefghijklmnopqrstuvwxyz'
    
        new_string_list = []
    
        for letter in string_list:
            new_string_list.append(alphabets[(alphabets.index(letter)+1) % len(alphabets)])
    
        return ''.join(new_string_list)
    
    lmao = raw_input('Enter somin\'')
    print str_changer(lmao)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2016-08-12
      • 2017-01-22
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多