2

I've got the list values stored as:

country = [u'USA']

How can I turn it into just 'USA'. I've tried str(country), but it didn't work.

1
  • 2
    "Get the first element of the list"? [u'USA'] is a list that contains a [unicode] string as the first and only element. The __str__ protocol for a list will output the "[..]" as well. Commented Dec 24, 2012 at 3:38

2 Answers 2

14

Apply str() on the element not on the list:

In [206]: country = [u'USA']

In [207]: country[0] = str(country[0])

In [208]: country
Out[208]: ['USA']

or may be you meant this:

In [217]: country = [u'USA']

In [218]: country = str(country[0])

In [219]: country
Out[219]: 'USA'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks...it was the second version. Thank you
5

country is a list that already contains Unicode strings. You don't need to convert it. The u'' syntax is just the item representation as a Python literal (how you would type it in a Python source code).

If you do need a bytestring; use .encode() method with an appropriate character encoding e.g.:

b = country[0].encode("ascii")

In general, structure a text processing code as Unicode sandwich i.e., use Unicode internally and use bytes only to communicate with outside world; don't mix the two.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.