【问题标题】:Python strip() unicode string?Python strip() unicode 字符串?
【发布时间】:2011-11-07 16:11:44
【问题描述】:

如何在 unicode 字符串上使用像 strip() 这样的字符串方法?你不能像普通字符串一样访问 unicode 字符串的字符吗? (例如:mystring[0:4])

【问题讨论】:

  • 你试过了吗? u'asdf '.strip()[2:] 对我来说非常好(它产生 u'df')。
  • u"Hallöle Wélt"[1:5] 也是如此。
  • 对我来说很好。你的具体问题是什么?
  • 如果您得到的答案之一解决了您的问题,请点击复选标记接受它。

标签: python string unicode strip


【解决方案1】:

只要它们实际上是unicode,而不是str,它就可以正常工作(注意:每个字符串文字必须前面有u,就像在这个例子中一样):

>>> a = u"coțofană"
>>> a
u'co\u021bofan\u0103'
>>> a[-1]
u'\u0103'
>>> a[2]
u'\u021b'
>>> a[3]
u'o'
>>> a.strip(u'ă')
u'co\u021bofan'

【讨论】:

    【解决方案2】:

    也许现在回答这个问题有点晚了,但如果你正在寻找库函数而不是实例方法,你也可以使用它。 只需使用:

    yourunicodestring = u'  a unicode string with spaces all around  '
    unicode.strip(yourunicodestring)
    

    在某些情况下使用它更容易,例如在地图函数中,例如:

    unicodelist=[u'a',u'   a   ',u' foo is just...foo   ']
    map (unicode.strip,unicodelist)
    

    【讨论】:

      【解决方案3】:

      你可以做每一个字符串操作,实际上在 Python 3 中,所有的 str 都是 unicode。

      >>> my_unicode_string = u"abcşiüğ"
      >>> my_unicode_string[4]
      u'i'
      >>> my_unicode_string[3]
      u'\u015f'
      >>> print(my_unicode_string[3])
      ş
      >>> my_unicode_string[3:]
      u'\u015fi\xfc\u011f'
      >>> print(my_unicode_string[3:])
      şiüğ
      >>> print(my_unicode_string.strip(u"ğ"))
      abcşiü
      

      【讨论】:

        【解决方案4】:

        请参阅Python docs on Unicode strings 和以下有关字符串方法的部分。 Unicode 字符串支持所有常用的方法和操作,就像普通的 ASCII 字符串一样。

        【讨论】:

          猜你喜欢
          • 2017-11-19
          • 2011-11-12
          • 2021-11-03
          • 2012-04-21
          • 1970-01-01
          • 1970-01-01
          • 2017-03-15
          • 1970-01-01
          相关资源
          最近更新 更多