【问题标题】:Can't remove some symbols from a long string [duplicate]无法从长字符串中删除某些符号[重复]
【发布时间】:2018-12-21 01:35:59
【问题描述】:

在过去的几个小时里,我一直在尝试一次性从长字符串中踢出一些符号,但我不知道如何删除它们。如果我使用.replace() 函数,这将是一种更丑陋的方法,因为符号的数量不止一个,而且函数变得过于冗长,无法覆盖所有符号。任何删除它们的替代方法都将受到高度赞赏。

这是我试过的:

exmpstr = "Hi there Sam! Don't you know that Alex (the programmer) created something useful or & easy to control"

print(exmpstr.replace("'","").replace("(","").replace(")","").replace("&",""))
print(exmpstr.replace("['()&]","")) #I know it can't be any valid approach but I tried

我想从该字符串中剔除这些符号 '()&,而不是我尝试使用 .replace() 函数的方式。

【问题讨论】:

    标签: python string python-3.x symbols


    【解决方案1】:

    您可以使用带有替换的 for 循环:

    for ch in "['()&]":
        exmpstr = exmpstr.replace(ch, '')
    

    或者你可以使用正则表达式

    import re
    exmpstr = re.sub(r"[]['()&]", "", exmpstr)
    

    【讨论】:

    • 感谢@nosklo 的解决方案。时机成熟时会接受的。
    • @RushabhMehta 我不同意回答问题比帮助更重要。如果需要,请随时关闭问题。
    • 而且,您是对所有其他答案投反对票的人吗?请阅读:meta.stackoverflow.com/questions/276122/…
    • @RushabhMehta 我已经读过了。我只是不同意不应该回答这些问题。不是每个人都同意这里的每个人。这就是我们投反对票的原因。我只对其中一个答案投了反对票,我认为那个没有帮助。
    【解决方案2】:

    实际上,您的第二次尝试已经非常接近了。使用正则表达式sub进行替换,可以这样做:

    import re
    regex = r"['()&]"
    
    test_str = "\"Hi there Sam! Don't you know that Alex (the programmer) created something useful or & easy to control\""
    subst = ""
    # You can manually specify the number of replacements by changing the 4th argument
    result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
    if result:
        print (result)
    

    如果您想用and 替换&,请运行另一个:

    result = re.sub(r" & ", " and ", test_str, 0, re.MULTILINE)
    

    并从第一个 regex character group ['()&] 中删除 &

    【讨论】:

      【解决方案3】:

      它也可以解决问题:

      exmpstr = "Hi there Sam! Don't you know that Alex (the programmer) created something useful or & easy to control"
      expectedstr = ''.join(i for i in exmpstr if i not in "'()&")
      print(expectedstr)
      

      【讨论】:

      • 在这个简单的例子中并不明显,但有时这是最好的方法!赞成。您可以删除[],因为不需要创建中间列表:''.join(i for i in exmpstr if i not in unwanted)
      • 感谢@nosklo 的支持。及时更新。
      猜你喜欢
      • 2013-01-05
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多