Python strip() unicode string?

寵の児 提交于 2019-12-07 05:27:17

问题


How can you use string methods like strip() on a unicode string? and can't you access characters of a unicode string like with oridnary strings? (ex: mystring[0:4] )


回答1:


It's working as usual, as long as they are actually unicode, not str (note: every string literal must be preceded by u, like in this example):

>>> 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:


You can do every string operation, actually in Python 3, all str's are 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ü



回答3:


Maybe it's a bit late to answer to this, but if you are looking for the library function and not the instance method, you can use that as well. Just use:

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

In some cases it's easier to use this one, for example inside a map function like:

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



回答4:


See the Python docs on Unicode strings and the following section on string methods. Unicode strings support all of the usual methods and operations as normal ASCII strings.



来源:https://stackoverflow.com/questions/7258411/python-strip-unicode-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!