Skip to content Skip to sidebar Skip to footer

Python Convert Unicode To String

I got my results from sqlite by python, it's like this kind of tuples: (u'PR:000017512',) However, I wanna print it as 'PR:000017512'. At first, I tried to select the first one in

Solution 1:

You're confusing the string representation with its value. When you print a unicode string the u doesn't get printed:

>>> foo=u'abc'>>> foo
u'abc'>>> print foo
abc

Update:

Since you're dealing with a tuple, you don't get off this easy: You have to print the members of the tuple:

>>> foo=(u'abc',)
>>> print foo
(u'abc',)
>>> # If the tuple really only has one member, you can just subscript it:>>> print foo[0]
abc
>>> # Join is a more realistic approach when dealing with iterables:>>> print'\n'.join(foo)
abc

Solution 2:

Don't see the problem:

>>> x = (u'PR:000017512',)
>>> print x
(u'PR:000017512',)
>>> print x[0]
PR:000017512
>>>

You the string is in unicode format, but it still means PR:000017512

Check out the docs on String literals

http://docs.python.org/2/reference/lexical_analysis.html#string-literals

Solution 3:

In [22]: unicode('foo').encode('ascii','replace') 
Out[22]: 'foo'

Post a Comment for "Python Convert Unicode To String"