我正在尝试从CNN创建一个新闻列表,并使用下面的当前代码,它工作正常,并给我这个输出:
America is doing better than we're being led to believe
2016 candidates' daughters step up on trail this week
Paralympics day seven: Highlights from Rio
When athletes can take drugs. What are Therapeutic Use Exemptions?
Israeli security agents partner with Volkswagen to make unhackable cars
Will Warren Buffett break his silence on Wells Fargo?
Caitlyn Jenner visits Hill to raise LGBT awareness
Businesses could pose conflicts of interest for a President Trump
UNC football player turns himself in on sexual battery charge
EU faces 'existential crisis,' warns European Commission head
Melania Trump releases letter from immigration attorney
以下是代码:
feed = feedparser.parse(cnnUrl)
incrementOne = 0
newsList = []
print "" #Formatting Purposes
print "News:"
for post in feed.entries:
if incrementOne < 11:
print post.title
incrementOne = incrementOne + 1
newsList.append(post.title)
#print newsList
问题是,一旦我取消注释要用于程序另一部分的newsList(最后一行),它就会给我一个输出带有我不想要的“你”:
America is doing better than we're being led to believe
2016 candidates' daughters step up on trail this week
Paralympics day seven: Highlights from Rio
When athletes can take drugs. What are Therapeutic Use Exemptions?
Israeli security agents partner with Volkswagen to make unhackable cars
Will Warren Buffett break his silence on Wells Fargo?
Caitlyn Jenner visits Hill to raise LGBT awareness
Businesses could pose conflicts of interest for a President Trump
UNC football player turns himself in on sexual battery charge
EU faces 'existential crisis,' warns European Commission head
Melania Trump releases letter from immigration attorney
[u"America is doing better than we're being led to believe", u"2016 candidates' daughters step up on trail this week", u'Paralympics day seven: Highlights from Rio', u'When athletes can take drugs. What are Therapeutic Use Exemptions?', u'Israeli security agents partner with Volkswagen to make unhackable cars', u'Will Warren Buffett break his silence on Wells Fargo?', u'Caitlyn Jenner visits Hill to raise LGBT awareness', u'Businesses could pose conflicts of interest for a President Trump', u'UNC football player turns himself in on sexual battery charge', u"EU faces 'existential crisis,' warns European Commission head", u'Melania Trump releases letter from immigration attorney']
一开始,有一个“你”,然后在每个新闻标题之前重复。
我的问题是为什么会发生这种情况以及如何解决
答案 0 :(得分:0)
字符串前面的u前缀只是告诉你它们是unicode字符串(报纸使用的不仅仅是ascii字符)。如果你实际打印每个字符串,这个你不会出现;它只是告诉你字符串是用unicode编码的。
试试这个:
for news in newsList:
print news
或
print '\n'.join(newsList)
你会注意到你在打印中实际上并没有显示出来。 Here是Python中unicode字符串的文档。
答案 1 :(得分:0)
您正在打印数组的表示(更确切地说,转换为str
,repr
可能是不同的输出)
如果您想打印没有unicode,引号和括号的列表,只需
print("\n".join(newsList))
这会将列表连接成一个字符串,用换行符分隔。
答案 2 :(得分:0)
正在发生的事情是你告诉解释器打印一个列表,并且解释器正在尽力通过调用它的repr
来表示一个Unicode字符串列表,这涉及到了hte {每个元素的{1}}。
如果您只想查看(说)以逗号分隔的字符串值列表,那么您应该使用
repr
您可以在上面的示例中使用您喜欢的任何分隔符字符串,而不是print ", ".join(newsList)
。