带占位符的字符串格式化
String formatting with placeholders
是否可以在字符串格式中使用占位符?一个例子可能会说明我的意思:
"some {plural?'people':'person'}".format(plural=True)
应该是"some people"。基本上,我可以在格式字符串中的两个选项之间切换,而不是直接提供所有值,例如:
"some {plural}".format(plural="people")
这听起来有点无用,但用例是包含多个单词的许多字符串,可能是复数,这将大大简化代码。
你可以使用三元:
plural = False
>>> print("some {people}".format(people='people' if plural else 'person'))
some person
您还可以创建一个字典,其中包含可以通过布尔值访问的单复数词元组对。
irregulars = {
'person': ['person', 'people'],
'has': ['has', 'have'],
'tooth': ['tooth', 'teeth'],
'a': [' a', ''],
}
plural = True
words = [irregulars[word][plural] for word in ('person', 'has', 'a', 'tooth')]
print('some {} {}{} crooked {}'.format(*words))
plural = False
words = [irregulars[word][plural] for word in ('person', 'has', 'a', 'tooth')]
print('some {} {}{} crooked {}'.format(*words))
# Output:
# some people have crooked teeth
# some person has a crooked tooth
这是可能的 在 Python 3.6 之后使用 f-strings:
plural = True
print(f"some { 'people' if plural else 'person' }")
请注意 a if condition else b
是一个 Python 表达式,而不是 f-string 功能,因此您可以在需要的任何地方使用 'thing' if plural else 'things'
,而不仅仅是在 f-strings 中.
或者,如果你有一个复数函数(可以只是一个 dict
查找),你可以这样做:
print(f"{ pluralize('person', plural) }")
是否可以在字符串格式中使用占位符?一个例子可能会说明我的意思:
"some {plural?'people':'person'}".format(plural=True)
应该是"some people"。基本上,我可以在格式字符串中的两个选项之间切换,而不是直接提供所有值,例如:
"some {plural}".format(plural="people")
这听起来有点无用,但用例是包含多个单词的许多字符串,可能是复数,这将大大简化代码。
你可以使用三元:
plural = False
>>> print("some {people}".format(people='people' if plural else 'person'))
some person
您还可以创建一个字典,其中包含可以通过布尔值访问的单复数词元组对。
irregulars = {
'person': ['person', 'people'],
'has': ['has', 'have'],
'tooth': ['tooth', 'teeth'],
'a': [' a', ''],
}
plural = True
words = [irregulars[word][plural] for word in ('person', 'has', 'a', 'tooth')]
print('some {} {}{} crooked {}'.format(*words))
plural = False
words = [irregulars[word][plural] for word in ('person', 'has', 'a', 'tooth')]
print('some {} {}{} crooked {}'.format(*words))
# Output:
# some people have crooked teeth
# some person has a crooked tooth
这是可能的 在 Python 3.6 之后使用 f-strings:
plural = True
print(f"some { 'people' if plural else 'person' }")
请注意 a if condition else b
是一个 Python 表达式,而不是 f-string 功能,因此您可以在需要的任何地方使用 'thing' if plural else 'things'
,而不仅仅是在 f-strings 中.
或者,如果你有一个复数函数(可以只是一个 dict
查找),你可以这样做:
print(f"{ pluralize('person', plural) }")