解决Python中unicode输出的问题
我编写了一些代码,将查询发送到谷歌并返回查询结果。显然,检索到的内容采用 unicode 格式,因此当我将它们放入列表中并打印此列表(整个列表在一起,而不是逐个成员)时,恼人的额外“u”总是在所有成员后面这个列表..我怎样才能摆脱它们?我尝试将整个文本转换为 ascii,但由于文本中存在一些非 ascii 字符(不同语言),因此失败,现在您知道我应该做什么才能获得更好的输出吗?我希望这个额外的“u”不会造成任何麻烦。谢谢
I have written some code which sends queries to google and returns the query results. Apparently the contents which are retrieved are in unicode format, so when I put them in a list for example and print this list (the whole list together and not member by member) an annoying extra 'u' is always behind all of the members in this list..How can I get rid of them? I tried to convert the whole text to ascii but because there are some non-ascii characters(different languages) is in the text it fails, now do u know what I should do to have a better output? and I hope this extra 'u' doesn't make any troubles. thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代替:
使用:
如果您希望将其全部保留在一行上,则可以使用
', '
代替'\n'
作为分隔符。如果您尝试在 Windows 控制台中显示 Unicode 字符,也可能会遇到问题。如果是这样,您可以使用例如 IDLE 来显示 Unicode 字符。或者,您可以转换为 ASCII 并忽略 ASCII 中不存在的字符:
Instead of:
Use:
You can use
', '
instead of'\n'
as the separator if you prefer to keep it all on one line.You may also have problems if you are trying to display Unicode characters in the Windows console. If so, you could use for example IDLE which can display Unicode characters. Alternatively you can convert to ASCII and ignore the characters that don't exist in ASCII:
如果你要对你的输出做任何有意义的事情,你必须决定你想要哪种输出编码。扔掉所有这些非 ASCII 字符甚至不是第二好的解决方案。
决定适当的输出编码(例如,对于 shell 输出,您的 shell 编码;对于 Web 输出,您的 Web 编码,最好的全能者是 UTF-8)并进行适当的编码:
', '.join(x.encode('utf) -a') for x in your_list)
(En-/解码)If your going to do anything meaningful with your output, you have to decide which output encoding you want. Throwing all those non-ascii characters away is not even the second best solution.
Decide for an appropiate output encoding (e.g. for shell output your shell encoding, for web output your web encoding, best all-rounder is UTF-8) and encode appropiately:
', '.join(x.encode('utf-a') for x in your_list)
(En-/Decoding )