Python中%的含义是什么?

问题描述

我在日志记录模块中看到了这样的%(asctime)s

%()s代替%s是什么意思?

我只知道%s的意思是“字符串”,在互联网上找不到关于%()s的其他信息。

解决方法

使用% form of Python string formatting将值插入字符串时,这是字符串格式化功能。您正在研究的情况允许通过提供字典并以格式字符串在该字典中指定键来从字典中获取命名值。这是一个示例:

values = {'city': 'San Francisco','state': 'California'}
s = "I live in %(city)s,%(state)s" % values
print(s)

结果:

I live in San Francisco,California
,

%(asctime)s是日志模块使用的占位符,用于获取'asctime' attribute of a LogRecord object

notation '%(key)s'用于标识映射中的键,并将其值插入格式字符串中。例如,假设一个名叫约翰的人,身高168厘米,体重72公斤。

person = {'name': 'john','height': 168,'weight': 72}

如果要打印其名称和权重,则无需指定插入的每个实例,也不需要考虑权重为整数的事实。您所需要做的就是指定所需的键(在%()s内),并提供映射,将这些项目存储在%之后。

>>> print('%(name)s,%(weight)s' % person)
john,72

此字符串格式设置方法类似于str.format()

>>> print('{name},{weight}'.format(**person))
john,72

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...