【问题标题】:Python, "replace" module usingPython,“替换”模块使用
【发布时间】:2018-03-13 13:47:26
【问题描述】:

我刚开始学习 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ün değil evvelsi gün",那么我的输出是 "Din diğil ivvilsi gin" 。但与此不同的是,我的输出是“Din değil evvelsi gin”。

我如何正确编码这个例子?

【问题讨论】:

    标签: python-3.x methods replace


    【解决方案1】:

    试试这个代码

    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)
    

    结果:Din diğil ivvilsi gin

    【讨论】:

      【解决方案2】:

      当您设置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
      

      【讨论】:

      • Yakir Tsuberi 的回答也是正确的。他只是替换了“原地”字符串,而我的则创建了一个新字符串并且不会与旧字符串混淆。
      【解决方案3】:

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

      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

      【讨论】:

        猜你喜欢
        • 2011-06-24
        • 2011-02-13
        • 1970-01-01
        • 2018-11-08
        • 2017-02-27
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        • 2011-01-04
        相关资源
        最近更新 更多