如何在python中更改此列表中的字母?

时间:2018-04-14 22:28:15

标签: python

所以我试图创建一个允许你在python中解码消息的程序。这是我到目前为止所得到的......

def decode():
    print("Let's see what she wanted to tell you.")
    time.sleep(2)

    messageOne= raw_input('Please paste the message: ')
    print("Decoding message now...")

    message= list(messageOne)

我想知道如何将列表中的单个字母取出并根据我想要的代码进行更改。 Aka我需要知道如何更改列表中的特定值。谢谢!

1 个答案:

答案 0 :(得分:0)

你的问题不是很清楚,基于我所看到你可以有不同的方式来取代字母。例如,让我们使用字符串s:

>>> s = 'Hello'
>>> s.replace('l','h')
Hehho

如果您只想替换给定字母的一个匹配项,请使用:

>>> s = 'Hello'
>>> s.replace('l','h', 1) #will only replace the first occurrence
Hehlo

您还可以将字符串转换为列表

>>> s = 'Hello'
>>> s = [x for x in s]
>>> s
['H', 'e', 'l', 'l', 'o']

在这里你可以用任何东西替换任何东西,如:

>>> s[3] = 'h'
>>> s
['H', 'e', 'l', 'h', 'o']

当您完成替换所需的任何内容后,您可以使用.join()方法再次将列表设为字符串:

>>> s = ''.join(s) #separator goes in between the quotes
>>> s
Helho