在字符串中插入重复变量

2024-04-24 22:11:42 发布

您现在位置: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)))


Tags: 方法字符串txtloglentimeaswith
3条回答

^{}中使用位置参数说明符:

>>> '{0} {0}, {1}!'.format('hello', 'world')
'hello hello, world!'
>>>

我喜欢使用格式方法:

'my-var-value : {}'.format(variable)

能够读取任何对象或数据类型并将其直接传递给字符串的格式

能够将变量传递给字符串而无需索引编号的格式

'my-var 1 : {} & my-var 2 : {}'.format(var1,var2)

如果您使用的是Python3.6,那么fstrings有一个特性

x = 5
print(f'Argument: {x}')

这将给你:

Argument: 5

相关问题 更多 >