【问题标题】:How to make string when a sentence has quotation marks or inverted commas? Python当句子有引号或引号时如何制作字符串? Python
【发布时间】:2019-02-07 01:24:43
【问题描述】:

例如我有一个句子如:

Jamie's car broke "down" in the middle of the street

如何在不手动删除引号和引号的情况下将其转换为字符串,例如:

'Jamies car broke down in the middle of the street' 

感谢任何帮助! 谢谢,

【问题讨论】:

    标签: python string python-3.x converters


    【解决方案1】:

    一个接一个地使用replace()

    s = """Jamie's car broke "down" in the middle of the street"""
    
    print(s.replace('\'', '').replace('"', ''))
    # Jamies car broke down in the middle of the street
    

    【讨论】:

      【解决方案2】:

      您可以使用正则表达式从字符串中删除所有特殊字符:

      >>> import re
      >>> my_str = """Jamie's car broke "down" in the middle of the street"""
      
      >>> re.sub('[^A-Za-z0-9\s]+', '', my_str)
      'Jamies car broke down in the middle of the street'
      

      【讨论】:

        【解决方案3】:

        试试这个:

        oldstr = """Jamie's car broke "down" in the middle of the street""" #Your problem string
        newstr = oldstr.replace('\'', '').replace('"', '')) #New string using replace()
        print(newstr) #print result
        

        这会返回:

        Jamies car broke down in the middle of the street
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-07
          • 2011-01-27
          • 2013-11-09
          • 2019-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-05
          相关资源
          最近更新 更多