大家好,我现在有这个:
import feedparser
d = feedparser.parse('http://store.steampowered.com/feeds/news.xml')
for i in range(10):
print d.entries[i].title
print d.entries[i].date
我如何制作它以使标题和日期在同一行?此外它不需要打印我只是在那里进行测试,我想将此输出转储到带有标题和日期的mysql数据库中,非常感谢任何帮助!
答案 0 :(得分:2)
如果您想在同一行上打印,只需添加一个逗号:
print d.entries[i].title, # <- comma here
print d.entries[i].date
要插入MySQL,你可以这样做:
to_db = []
for i in range(10):
to_db.append((d.entries[i].title, d.entries[i].date))
import MySQLdb
conn = MySQLdb.connect(host="localhost",user="me",passwd="pw",db="mydb")
c = conn.cursor()
c.executemany("INSERT INTO mytable (title, date) VALUES (%s, %s)", to_db)
答案 1 :(得分:0)
关于你的实际问题:如果你想用逗号连接两个字符串,你可以使用这样的东西:
print d.entries[i].title + ', ' + str(d.entries[i].date)
请注意,我已使用str
将日期转换为字符串。
您也可以使用字符串格式:
print '%s, %s' % (d.entries[i].title, str(d.entries[i].date))
或者在Python 2.6或更新版本中使用str.format
。
但是如果你想将它存储在数据库中,最好使用两个单独的列,而不是将两个值组合成一个字符串。您可能需要考虑调整架构以允许此操作。