Eth*_*thr 2 python string format list python-3.x
如何打印列表的下一个值代替%s?下面的代码显示了我希望得到的结果,但我不想手动编写每一步.
hours=["14","15","18","30"]
print (("%s:%s-%s:%s")%(hours[0],hours[1],hours[2],hours[3]))
Run Code Online (Sandbox Code Playgroud)
有没有办法做这样的事情:
print (("%s:%s-%s:%s")%hours)
Run Code Online (Sandbox Code Playgroud)
并使其工作?
您可以直接在Python 3中使用解包:
>>> ("%s:%s-%s:%s")%(*hours,)
'14:15-18:30'
Run Code Online (Sandbox Code Playgroud)
或者转换为Python 2中的元组:
>>> ("%s:%s-%s:%s")%tuple(hours)
'14:15-18:30'
Run Code Online (Sandbox Code Playgroud)