将两条打印合并为一行并插入MySQL数据库
大家好,我现在有这个:
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数据库里,包含标题和日期,任何帮助都非常感谢!
2 个回答
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
。
不过,如果你想把这些数据存到数据库里,可能更好用两个单独的列,而不是把两个值合成一个字符串。你可以考虑调整你的数据库结构来支持这个。
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)