Python string unicode string?

How can you use string methods like strip () in a unicode string? and can you not access the characters of a unicode string, for example with the help of oridnary strings? (for example: mystring [0: 4])

+4
source share
4 answers

It works as usual, as long as they are actually unicode , not str (note: each string literal must be preceded by u , as 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' 
+8
source

You can perform every line operation, actually in Python 3, all str 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ü 
+2
source

See Python Docs in Unicode Strings and the next section on string methods. Unicode strings support all common methods and operations like regular ASCII strings.

+1
source

It may be a bit late to answer this, but if you are looking for a library function, not an instance method, you can also use it. Just use:

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

In some cases, it is easier to use, for example, inside a display function, for example:

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

All Articles