使用占位符进行字符串格式

问题描述 投票:0回答:2

是否可以在字符串格式中使用占位符?一个例子可能会显示我的意思:

"some {plural?'people':'person'}".format(plural=True)

应该是“有些人”。基本上,我可以在格式字符串中切换两个选项,而不是直接提供所有值,例如:

"some {plural}".format(plural="people")

这可能听起来有点无用,但用例是许多字符串,其中有几个单词可能是复数,这将大大简化代码。

python string-formatting ternary-operator
2个回答
2
投票

在使用f-strings的Python 3.6之后,这是可能的:

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) }")

1
投票

你可以使用三元:

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
© www.soinside.com 2019 - 2024. All rights reserved.