如何在python中更改此列表中的字母?
因此,我正在尝试制作一个程序,允许您用python解码消息。这是我到目前为止得到的如何在python中更改此列表中的字母?,python,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)
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)
我想知道我将如何在列表中的单个字母,并根据我想要的代码更改它们。我需要知道如何更改列表中的特定值。谢谢 你的问题不是很清楚,根据我的了解,你可以用不同的方式替换字母。例如,让我们使用字符串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
string.replace()?代码是如何工作的?string.replace在执行诸如用3s替换所有Es的操作时会起作用。@raul.vila所以现在我合并了它,但它返回了一个错误:“AttributeError:'list'对象没有属性'replace'”messageOne=messageOne.replace(“xxx”,“yyy”)#如果messageOne是“我的xxx字符串”,那么它将被替换为“我的yyy字符串”“基于我想要的代码”是非常模糊的。你是否总是用一个字符替换另一个字符,没有比这更复杂的了?