gpt4 book ai didi

python - 如何遍历字符串并正确替换 python 中的特定字符?

转载 作者:行者123 更新时间:2023-12-05 02:17:47 24 4
gpt4 key购买 nike

我正在尝试在 python 中创建一种可发音的加密语言。我想遍历一个字符串并更改,即只是一些元音。

我认为这可以用数组chars["a","o"]来完成,其中第一个字母应该替换为第二个。

我正在试验这段代码。

import string

string = "Hello, my name is fesker"
chars =[
["a","o"],
["e","i"],
["i","u"],
["o","e"],
["u","a"],
["H","J"],
]

for i in range(len(string)):
print(string[i])
replaced=False

for x in range(len(chars)):

if string[i] in chars[x][0] and replaced == False:
string = string.replace(string[i],chars[x][1])
replaced=True
print("Replace",chars[x][0],"with",chars[x][1])


print(string)

我不明白这一点,我认为函数应该是正确的,但字符串替换给了我不同的输出。最后一句应该读作“Jille, my nomi us fosker”

但是 python shell 给了我“Jelle, my neme es fesker”:

    H
Replace H with J
e
Replace e with i
l
l
o
Replace o with e
,

m
y

n
a
Replace a with o
m
i
Replace i with u

u
Replace u with a
s

f
a
Replace a with o
s
k
o
Replace o with e
r
Jelle, my neme es fesker

我做错了什么?

最佳答案

One line solution:

print(''.join(char.get(s, s) for s in string))

如果:

string = "Hello, my name is fesker"

char={"a":"o","e":"i","i":"u","o":"e","u":"a","H":"J"}

Detailed solution:

I have some suggestions for your code:

不要在那里使用 .replace() 它会替换所有匹配的字符

Use dict instead of list there if you want key,value pair.
char={"a":"o","e":"i","i":"u","o":"e","u":"a","H":"J"}

因为字符串是不可变的,所以如果你想修改它,第二个转换列表中的字符串。

string=list(string)

这是经过一些修改后的解决方案:

string = "Hello, my name is fesker"

char={"a":"o","e":"i","i":"u","o":"e","u":"a","H":"J"}

string=list(string)

for index,item in enumerate(string):
for key,value in char.items():
if item==key:
string[index]=value

print("".join(string))

输出:

Jille, my nomi us fiskir

关于python - 如何遍历字符串并正确替换 python 中的特定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47088629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com