【发布时间】:2017-11-03 04:46:03
【问题描述】:
我正在尝试在 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
我做错了什么?
【问题讨论】:
-
string = string.replace(string[i],chars[x][1])"Hello"这个字符串中,'e'这个字母在'e' -> 'i' -> 'u' -> 'a' -> 'o' -> 'e'这个循环中,所以看起来没有变化,但实际上已经改变了5次。
标签: python string replace char