在python中按行连接两个字符串
我有两个字符串,如下所示:在python中按行连接两个字符串,python,string,python-2.7,Python,String,Python 2.7,我有两个字符串,如下所示: comstr = ['year', 'doy', 'd_lon', 'd_lat'] datstr = ['2015', '112', '1.78218', '1.78218'] 'year', 'doy', 'd_lon', 'd_lat' # 1st row '2015', '112', '1.78218', '1.78218' # 2nd row 如何连接这两个字符串?我希望结果如下: comstr = ['year', 'doy', 'd_lo
comstr = ['year', 'doy', 'd_lon', 'd_lat']
datstr = ['2015', '112', '1.78218', '1.78218']
'year', 'doy', 'd_lon', 'd_lat' # 1st row
'2015', '112', '1.78218', '1.78218' # 2nd row
如何连接这两个字符串?我希望结果如下:
comstr = ['year', 'doy', 'd_lon', 'd_lat']
datstr = ['2015', '112', '1.78218', '1.78218']
'year', 'doy', 'd_lon', 'd_lat' # 1st row
'2015', '112', '1.78218', '1.78218' # 2nd row
您可以使用:
com_list = ['year', 'doy', 'd_lon', 'd_lat']
dat_list = ['2015', '112', '1.78218', '1.78218']
for strings in [com_list, dat_list] :
print(", ".join(["'%s'" % string for string in strings]))
它输出:
'year', 'doy', 'd_lon', 'd_lat'
'2015', '112', '1.78218', '1.78218'
这些是名单。您可以使用
“”.join(“{}”.format(x)for x in comstr)
这些是列表,其元素是列表。另外,你想要的结果应该是一个列表?@JuanT:list of strings.@Jean-Françoisfar:我想你错过了一个,
@EricDuminil是正确的。我没有投反对票,但我不会依赖repr
完成这项任务。@Jean-Françoisfar:更新。为什么不呢?我觉得这太过分了。此外,如果较新版本的python更改字符串的repr
,则程序将出错。顺便说一句:最好做“,”。加入([“'%s'”字符串中的字符串的字符串])
<代码>加入在listcomps上运行得更快。