我有以下脚本,我使用SQL查询来获取所需的信息,它工作正常,但信息不是预期的格式,请参阅下面的预期输出,它应该是空格分隔列表,没有新的字符( " \ n")最后,如何以所需的格式获得输出?
db = MySQLdb.connect(host="dbhost",user="username",port=3339,passwd="passwordname",db="dbname")
# prepare a cursor object using cursor() method
cursor = db.cursor()
gerritlist = []
# Prepare SQL query to get the gerrits from the database.
sql_get = """SELECT gerrit_id
FROM dbname.gerrit_submit_table
where (SI='%s'
and component='%s')"""%(SI,component)
#print sql_get
rows = cursor.execute(sql_get)
gerrits = cursor.fetchall()
print "GERRITS FROM DB"
print gerrits
输出: -
GERRITS FROM DB
(('1258565',), ('1279604',))
EXPECTEDOUTPUT :-(空格分隔列表,最后没有新字符(\ n))
1258565 1279604
答案 0 :(得分:0)
最后,只需这样做:
print ' '.join(item[0] for item in gerrits),
或者这个:
print ' '.join(item[0] for item in gerrits).rstrip('\r\n')
或者,如果您想将值存储在列表中(例如,您拥有的gerritlist
变量):
gerritlist = [item[0] for item in gerrits]
答案 1 :(得分:0)
以下会工作,但我不确定新的部分,也许其他人可以用更好的方式回应
def listtostring(list):
gerrits = ''
if len(list):
value = len(list) - 2
gerrits += list[value]
for i in range(1, len(list)):
value -= 1
gerrits += ' ' + list[value]
else :
print "No gerrits in list to parse"
return gerrits
for row in gerrits:
for gerrit in row:
gerritlist.append(gerrit)
gerritlist_str = listtostring(gerritlist)
print gerritlist_str