我是django/python的noob,我在github中看到一段关于“导出Vcard”文件的代码,我的问题是关于程序员替换字符串变量中变量值的部分:
admin.py:
output = ""
for person in queryset.all():
person_output = """BEGIN:VCARD
VERSION:3.0
N:{last_name};{first_name}
FN:{first_name} {last_name}
TEL;TYPE=HOME,VOICE:{phone}
TEL;TYPE=WORK,VOICE:{secondary_phone}
EMAIL:{email}
REV:{rev}
END:VCARD"""
# how can replace value when the source is string?!
person_output = person_output.format(
first_name = person.first_name,
last_name = person.last_name,
phone = person.phone,
secondary_phone = person.secondary_phone,
email = person.email,
rev = d.strftime('%Y%M%d%H%f'),
)
有谁能解释一下这是怎么可能的,并让我知道任何关于它的python/django文档吗?谢谢
这只是简单的string formatting [pyformat]。可以根据Python documentation和PEP-3101中解释的格式指定字符串,然后通过调用
my_string.format(..)
将字符串中的某些部分替换为其他部分事实上,它是介于“三重引号”之间的字符串,这没有任何区别,因为它只是一个字符串
整个格式在PEP-3101中进行了解释,但简而言之,如果您编写
{var_name}
,然后使用命名参数.format(var_name=value)
对其进行格式化,则{var_name}
将替换为value
。但是也有一些例外,例如{{}}
被{}
替换,并且格式允许正确对齐数字,等等由于python-3.6,可以使用f-strings [real Python]更有效地执行格式化
相关问题 更多 >
编程相关推荐