从字符串字符中删除前缀u

2024-04-20 14:10:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我正在努力检索电影类型的部分代码。在

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']

我想去掉那些u前缀。在

期望输出:

^{pr2}$

Tags: 代码in类型for电影contentsallfind
3条回答

字符串中的前缀u表示Unicode

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

不需要移除它

实际上不需要从字符串中删除unicode,但是如果您仍然坚持这样做,您可以使用map()或list comprehension。在

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

或列表组件

^{pr2}$

u表示这些字符串被编码为unicode。在

如果要删除它,只需执行以下操作:

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

注意事项:

  • 只有当字符串中的所有字符都是ascii字符时,这才有效。在
  • 正如其他人评论的那样,u不是字符串的一部分,它只是表示其编码,因此没有理由删除它。在

相关问题 更多 >