【问题标题】:How to remove special characters from the beginning of a string in Python如何在 Python 中删除字符串开头的特殊字符
【发布时间】:2011-11-13 13:58:47
【问题描述】:

我正在从 XML 中获取我的数据,这些数据可能有时会在开头包含特殊字符,例如:

'这是一个示例标题或%&*我不知道这是不是文字

我尝试过: title[0].isstring() or title[0].isdigit() 然后删除字符。但是如果开头有多个特殊字符,那我该如何删除呢?我需要一个 for 循环吗?

【问题讨论】:

  • 我建议您检查一下为什么要从 XML 文档中获取“特殊字符” 文档是否编码为 utf-8 - 您是否正确解码了 xml?有时看到特殊字符通常是编码问题,而不是 xml 内容的问题。

标签: python regex string substring


【解决方案1】:

使用 strip 函数从字符串的开头和结尾删除任何特殊字符。 前任。

str = ").* this is text .("
str.strip(")(.* ")

Output: 'this is text'

如果要从字符串的开头删除,请使用 lstrip() 例如。

str = ").* this is text .("
str.lstrip(")(.* ")

Output: 'this is text .('

如果要从字符串末尾删除,请使用 rstrip() 例如。

str = ").* this is text .("
str.rstrip(")(.* ")

Output: ').* this is text'

【讨论】:

    【解决方案2】:

    如果您只想删除几种特定类型的字符,请使用lstrip()(“左条”)。

    例如,如果您想删除任何以 %&* 开头的字符,您可以使用:

    actual_title = title.lstrip("%&*")
    

    另一方面,如果您想删除任何属于某个集合的字符(例如字母数字),那么 Tim Pietzcker 的解决方案中指定的正则表达式解决方案可能是最简单的方法.

    【讨论】:

      【解决方案3】:
      >>> import re
      >>> re.sub(r'^\W*', '', "%&*I don't know if this is the text")
      "I don't know if this is the text"
      
      #or
      
      >>> "%&*I don't know if this is the text".lstrip("!@#$%^&*()")
      "I don't know if this is the text"
      

      【讨论】:

      • \W+ 更好。 \W* 也匹配空字符串,因此即使没有要替换的内容,也必须进行替换操作和字符串重新分配。
      【解决方案4】:

      你可以使用正则表达式:

      import re
      mystring = re.sub(r"^\W+", "", mystring)
      

      这会删除字符串开头的所有非字母数字字符:

      说明:

      ^   # Start of string
      \W+ # One or more non-alphanumeric characters
      

      【讨论】:

        猜你喜欢
        • 2020-04-16
        • 2015-11-11
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多