如何在输入中将一个 str 替换为另一个 str

问题描述 投票:0回答:1

如何用另一个字符串替换列表中的字符串?例如,我想将“A”替换为“[c:16399:0/]”,将“B”替换为 “[c:16400:0/]”。我想对用户输入中的每个字符执行此操作。我尝试过 .replace 功能,但是一次只能替换 1 个字符,而且我不知道如何同时替换多个字符。

我希望这次编辑能澄清我的问题,谢谢! picture of the code i have so far

python translation
1个回答
0
投票

使用函数将字符转换为其他字符串

def newstring(c):
    return f"[c:{16399+ord(c)-ord('A')}:0/]"

startstring = "ABCD WORLD"
transformed = [ newstring(c) for c in startstring ]

如果你想要一个新字符串,请使用

transformed = ''.join((newstring(c) for c in startstring))
© www.soinside.com 2019 - 2024. All rights reserved.