【问题标题】:Remove extra characters in the string in Python在 Python 中删除字符串中的多余字符
【发布时间】:2013-05-07 14:51:01
【问题描述】:

我有几个字符串(每个字符串都是一组单词),其中包含特殊字符。我知道使用 strip() 函数,我们可以从任何字符串中删除所有出现的仅一个特定字符。现在,我想删除一组特殊字符(包括 !@#%&*()[]{}/? )等。

从字符串中删除这些不需要的字符的最佳方法是什么。

in-str = "@John,这是一个很棒的#week-end%,about () 你怎么样?

out-str = "John,这是一个美妙的周末,你呢?"

【问题讨论】:

  • 如果没有正则表达式,` () ` 将特别难以摆脱。
  • 请问为什么你想这样做?特别是,如果您想防止代码注入攻击,您可能更愿意转义特殊字符而不是删除它们。具体情况取决于具体的应用程序。

标签: python string strip


【解决方案1】:

strip 函数只删除前导和尾随字符。 出于您的目的,我将使用 python set 来存储您的字符,迭代您的输入字符串并从set 中不存在的字符创建新字符串。根据其他stackoverflow article,这应该是有效的。最后,只需通过巧妙的" ".join(output_string.split()) 构造删除双空格即可。

char_set = set("!@#%&*()[]{}/?<>")
input_string = "@John, It's a fantastic #week-end%, How about () you"
output_string = ""

for i in range(0, len(input_string)):
    if not input_string[i] in char_set:
        output_string += input_string[i]

output_string = " ".join(output_string.split())
print output_string

【讨论】:

    【解决方案2】:
    import string
    
    s = "@John, It's a fantastic #week-end%, How about () you"
    for c in "!@#%&*()[]{}/?<>":
        s = string.replace(s, c, "")
    
    print s
    

    打印“约翰,这是一个美妙的周末,你呢?”

    【讨论】:

      【解决方案3】:

      试试这个:

      import re
      
      foo = 'a..!b...c???d;;'
      chars = [',', '!', '.', ';', '?']
      
      print re.sub('[%s]' % ''.join(chars), '', foo)
      

      我想这就是你想要的。

      【讨论】:

      • 顺便说一句,我建议构建 foreach 循环不接受的字符数组,或以类似方式确保动态编辑受限字符。
      【解决方案4】:

      试试

      s = "@John, It's a fantastic #week-end%, How about () you"
      chars = "!@#%&*()[]{}/?<>"
      s_no_chars = "".join([k for k in s if k not in chars])
      s_no_chars_spaces = " ".join([ d for d in "".join([k for k in s if k not in chars]).split(" ") if d])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-16
        • 1970-01-01
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-10
        相关资源
        最近更新 更多