0

This is the partial code I am working where I am trying to retrieve the genres of movies.

genres = tr.find('span', 'genre').find_all('a')
genres = [g.contents[0] for g in genres]
print genres

[u'Animation']
[u'Comedy']
[u'Comedy', u'Romance']

I want to remove those u prefix.

Desired output:

['Animation']
['Comedy']
['Comedy', 'Romance']
4
  • 2
    why you wan to remove it??, it dosent effect anything Commented Feb 10, 2015 at 21:45
  • @ Hackaholic, this is required for project. Commented Feb 10, 2015 at 21:47
  • 1
    Are you trying to generate output (e.g., to a file) where these characters would screw up parsing? The prefix 'u' is informational so you know the type of string that Python is outputting. It's similar to the 'L' that's appended to Python long integers. Commented Feb 10, 2015 at 21:47
  • How can I make use of .encode("ascii", "ignore") here? Commented Feb 10, 2015 at 22:07

3 Answers 3

2

The u means that those strings are codified as unicode.

If you want to remove it you can just do:

genres = [str(g.contents[0]) for g in genres]

Notes:

  • This will only work if all characters in the string are ascii characters.
  • As others commented, the u is not part of the string, it just indicates its codification, so there is no reason to remove it.
Sign up to request clarification or add additional context in comments.

1 Comment

As with limelights's response, this will only work if the unicode strings contain only ascii characters.
2

There is no need to actually remove the unicode from your string but if you're still set on doing it, you can either use map() or a list comprehension.

map(str, [u'Comedy', u'Romance'])
>> ['Comedy', 'Romance']

or the list comp

l = [str(x) for x in ['Comedy', 'Romance']]

1 Comment

That is totally correct, I haven't had time to write it in my answer yet. Thanks!
1

the prefix u in the string represent Unicode

>>> unicode("abc")
u'abc'

No need to remove it

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.