Python,“替换”模块使用

时间:2018-03-13 13:47:27

标签: python-3.x methods replace

我刚开始学习Python。当我想使用“替换”模块编写一个小的示例代码时遇到了问题。这是我的代码:

char_arr = "Dün değil evvelsi gün"

vowel_in_tr = "aeıioöuü"
for i in vowel_in_tr: 
    for k in char_arr:                          #search a vowel
        if k == i:                              #if found a vowel
new = char_arr.replace(str(k),"i")  #change the vowel to "i"

print(new) #Output is new char_arr

我想如果我的char_arr变量是“Dündğilevvelsigün”,那么我的输出是“Dindiğilivvilsigin”。但不是那样,我的输出是“Dindeğilevvelsigin。”

我如何正确编码此示例?

3 个答案:

答案 0 :(得分:0)

试试此代码

char_arr = "Dün değil evvelsi gün"

vowel_in_tr = "aeıioöuü"
for i in char_arr:
    if i in vowel_in_tr:
        char_arr = char_arr.replace(i, 'i')

print(char_arr)

结果:Dindiğilivvilsigin

答案 1 :(得分:0)

当您设置new = char_arr.replace(str(k), "i")时,它不会保留替换后的字符串。 char_arr没有更新。以下是一些可以解决问题的代码。

char_arr = "Dün değil evvelsi gün"
new_string_arr = []

vowel_in_tr = "aeıioöuü"
for ch in char_arr: # walk through the char_arr
    if ch in vowel_in_tr: # if the character is in the vowel array
        new_string_arr.append('i')  # add an i to the new string "i"
    else: # otherwise
        new_string_arr.append(ch) # add the original character

# join together the new array with nothing in between characters
new_string = ''.join(new_string_arr)

print(new_string) #Output is new_string

答案 2 :(得分:0)

尝试将替换的字符串保存在另一个变量中:

char_arr = "Dün değil evvelsi gün"
vowel_in_tr = "aeıioöuü"

result = char_arr

for a in char_arr: 
  if a in vowel_in_tr:
    result = result.replace(a , 'i')

print (result)

它无效,因为每次使用new = char_arr.replace(str(k),"i")时都会为您的变量分配一个“新”字符串,因为char_arr值为Dün değil evvelsi gün