unicode – Python string prints as [uString]

unicode – Python string prints as [uString]

[uABC] would be a one-element list of unicode strings. Beautiful Soup always produces Unicode. So you need to convert the list to a single unicode string, and then convert that to ASCII.

I dont know exaxtly how you got the one-element lists; the contents member would be a list of strings and tags, which is apparently not what you have. Assuming that you really always get a list with a single element, and that your test is really only ASCII you would use this:

 soup[0].encode(ascii)

However, please double-check that your data is really ASCII. This is pretty rare. Much more likely its latin-1 or utf-8.

 soup[0].encode(latin-1)


 soup[0].encode(utf-8)

Or you ask Beautiful Soup what the original encoding was and get it back in this encoding:

 soup[0].encode(soup.originalEncoding)

You probably have a list containing one unicode string. The repr of this is [uString].

You can convert this to a list of byte strings using any variation of the following:

# Functional style.
print map(lambda x: x.encode(ascii), my_list)

# List comprehension.
print [x.encode(ascii) for x in my_list]

# Interesting if my_list may be a tuple or a string.
print type(my_list)(x.encode(ascii) for x in my_list)

# What do I care about the brackets anyway?
print , .join(repr(x.encode(ascii)) for x in my_list)

# Thats actually not a good way of doing it.
print  .join(repr(x).lstrip(u)[1:-1] for x in my_list)

unicode – Python string prints as [uString]

import json, ast
r = {uname: uA, uprimary_key: 1}
ast.literal_eval(json.dumps(r)) 

will print

{name: A, primary_key: 1}

Leave a Reply

Your email address will not be published. Required fields are marked *