python - 将重复变量插入字符串
问题描述
有没有更好的方法将变量插入字符串?
比如说,比……更少重复的东西
with open('zlog.txt', 'a') as log:
log.write('[ %s ] Finished scrolling.\n[ %s ] #%s clicks.\n[ %s ] Number of Elements: %s\n' % (finish_time, finish_time, str(x), finish_time, str(len(elements))))
我不断重复使用finish_time
,以便为日志中的条目添加时间戳。
... % (finish_time, finish_time, str(x), finish_time, str(len(elements)))
解决方案
在 中使用位置参数说明符format
:
>>> '{0} {0}, {1}!'.format('hello', 'world')
'hello hello, world!'
>>>