【问题标题】:Python remove all apostrophes from a stringPython从字符串中删除所有撇号
【发布时间】:2015-03-12 14:44:45
【问题描述】:

我想删除大量字符串中所有出现的单撇号和双撇号。

我试过这个-

mystring = "this string shouldn't have any apostrophe - \' or \" at all"
print(mystring)
mystring.replace("'","")
mystring.replace("\"","")
print(mystring)

但它不起作用!我错过了什么吗?

【问题讨论】:

  • mystring.replace("'", "") 将打印编辑后的字符串。

标签: python


【解决方案1】:

Replace 不是就地方法,这意味着它返回一个您必须重新分配的值。

mystring = mystring.replace("'", "")
mystring = mystring.replace('"', "")

此外,您可以像这样使用单引号和双引号来避免转义序列。

【讨论】:

  • 值得一提的是为什么替换不是就地 - Python 字符串是不可变的。
【解决方案2】:

字符串在 python 中是不可变的。所以不能进行就地替换。

f = mystring.replace("'","").replace('"', '')
print(f)

【讨论】:

    【解决方案3】:

    这对我的情况终于奏效了。

    #Python 2.7
    import string
    
    companyName = string.replace(companyName, "'", "")
    

    【讨论】:

      【解决方案4】:

      使用正则表达式是最好的解决方案

      import re
      REPLACE_APS = re.compile(r"[\']")
      
      text = " 'm going"
      text = REPLACE_APS .sub("", text)
      

      input = "'我要去" 输出 = "m 去"

      【讨论】:

        猜你喜欢
        • 2021-12-17
        • 2015-07-07
        • 2017-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多