【问题标题】:How to implement a function which receives a string and replaces all `"` symbols with `'` and vise versa?如何实现一个接收字符串并将所有 `\"` 符号替换为 `\'` 的函数,反之亦然?
【发布时间】:2022-11-10 13:43:41
【问题描述】:

str = input("Something: ")


modified_str = ''


for char in range(0, len(str)):
    # checking if the character at char index is equivalent to 'a'
    if(str[char] == '"'):
        # append $ to modified string
        modified_str += "'"
    elif(str[char] == "'"):
        modified_str == '"'
    else:
        # append original string character
        modified_str += str[char]

print("Modified string : ")
print(modified_str)

我的输出结果是: 某事:dd"""ddd'''ddd 修改后的字符串: dd'''dddddd - 但为什么它不替换 ' 字符

【问题讨论】:

标签: python string replace character


【解决方案1】:

正如chepner 已经提到的,您需要在elif 分支中使用+= 而不是==


你也可以缩短代码并实现一个稍微不同的、更 Pythonic 的逻辑:

  1. 查找" 的索引
  2. 将所有' 替换为"
  3. 将第一步找到的索引处的所有字符设置为'
    input = "'test' it or test "this""
    
    tmp_idx = [pos for pos, char in enumerate(input) if char == "'"]
    
    result = list(input.replace(""", "'"))
    for idx in tmp_idx:
        result[idx] = """
    result = "".join(result)
    
    print(result)
    

    这将执行您正在寻找的替换:

    输入:'test' it or test "this"

    输出:"test" it or test 'this'

【讨论】:

    【解决方案2】:

    这最好用str.translate 解决。

    您可以使用str.maketrans 创建一个转换表,它允许您以几种不同的方式定义它。在您的情况下,最易读的可能是使用 dict 将每个字符映射到其翻译:

    conversion_table = str.maketrans({'"':"'", "'":'"'})
    

    您只需要使用要转换的字符串的translate 方法,并使用此表作为参数:

    print('I'm getting "converted"'.translate(conversion_table))
    
    # I"m getting 'converted'
    

    【讨论】:

      【解决方案3】:

      我是编程新手,我有同样的任务,但我需要把它作为一个函数,有人可以帮我吗?所以这是我的代码,但它不起作用: def 替换器(s:str)-> str: tmp_idx = [pos for pos, char in enumerate(s) if char == "'"]

      result = list(s.replace(""", "'"))
      for idx in tmp_idx:
          result[idx] = """
      result = "".join(result)
      return ''
      

      replacer("'test' 它或测试 "this"")

      【讨论】:

        猜你喜欢
        • 2017-10-06
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 2019-12-27
        • 1970-01-01
        相关资源
        最近更新 更多