Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strip() unicode string?

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] )

like image 357
nepwk Avatar asked Aug 31 '11 14:08

nepwk


People also ask

Can you use strip on a string Python?

The string strip() method in python is built-in from Python. It helps the developer to remove the whitespaces or specific characters from the string at the beginning and end of the string. Strip() method in string accepts only one parameter which is optional and has characters.

What does Unicode () do in Python?

If encoding and/or errors are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised.


2 Answers

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'
like image 186
Gabi Purcaru Avatar answered Sep 21 '22 12:09

Gabi Purcaru


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)
like image 22
pdepmcp Avatar answered Sep 22 '22 12:09

pdepmcp