【问题标题】:How do i iterate through a string and replace specific chars in python correctly?如何遍历字符串并正确替换 python 中的特定字符?
【发布时间】: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


【解决方案1】:

一线解决方案:

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"}

详细解决方案:

我对你的代码有一些建议:

不要使用.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

【讨论】:

  • 您的第一个解决方案是一个很棒的单线!
【解决方案2】:

您的问题:

string = string.replace(string[i],chars[x][1]) "Hello"这个字符串中,'e'这个字母在'e' -> 'i' -> 'u' -> 'a' -> 'o' -> 'e'这个循环中,所以看起来没有变化,但实际上已经改变了5次。

可能的解决方案:

使用您的“Hello”示例将“e”替换为“i”:

  • 如果您只想替换出现的 n 个字母,可以使用 .replace() 的第三个参数,可以是 .replace("e", "i", 1)。注意:这可能是最糟糕的解决方案,但我提到它是为了让您了解 .replace() 的工作原理。

  • 您可以在循环中一次替换一个字符。在下面的示例中,当然将数字 1 和 2 替换为 ii + 1。如果您选择此解决方案,请记住,当您遍历字符串或数组时,您将检查每个字母以查看是否需要先替换它。如果需要替换,使用 O(1) 查找(使用哈希字典)找到替换字符,然后替换为以下示例之一。

代码:

string = "{}{}{}".format(string[:1], "i", string[2:])
  • 或者您可以将字符串转换为可变数组。

代码:

string = list(string)
# or string = [i for i in string]
# ["H", "e", "l", "l", "o"]
string[1] = "i"
# ["H", "i", "l", "l", "o"]
string = "".join(string)
# "Hillo"
  • 根据Ayodhyankit Paul,您绝对应该使用字典来存储您的配对。此外,这是我解释的循环的 1 线性解决方案,他解释了:

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

【讨论】:

    【解决方案3】:
    string = "Hello, my name is fesker"
    chars ={
            "a": "o",
            "e": "i",
            "i": "u",
            "o": "e",
            "u": "a",
            "H":"J",}
    
    res_string = ""
    
    for char in string:
        res = char
        if char in chars.keys():
            res = chars[char]
    
        res_string += res
    
    print(res_string)
    

    这里是另一种解决方案。

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 2019-03-28
      • 2018-07-06
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多