如何实现条件字符串格式化?

时间:2012-02-11 23:16:00

标签: python string-formatting

我一直在用Python编写基于文本的游戏,我遇到过一个实例,我希望根据一组条件对字符串进行不同的格式化。

具体来说,我想显示描述房间内物品的文字。我希望在房间的描述中显示这个,当且仅当有问题的物品对象位于房间对象的物品清单中时。它的设置方式,我觉得简单地连接基于条件的字符串不会按照我的意愿输出,并且最好为每种情况设置一个不同的字符串。

我的问题是,是否有基于布尔条件结果格式化字符串的pythonic方法?我可以使用for循环结构,但我想知道是否有更容易的东西,类似于生成器表达式。

我正在寻找与此类似的东西,以字符串形式

num = [x for x in xrange(1,100) if x % 10 == 0]

作为我的意思的一般例子:

print "At least, that's what %s told me." %("he" if gender == "male", else: "she")

我意识到这个例子不是有效的Python,但它总体上显示了我正在寻找的东西。我想知道布尔字符串格式是否有任何有效的表达式,类似于上面的。 在搜索了一下之后,我无法找到任何与条件字符串格式有关的内容。我确实在格式字符串上找到了几个帖子,但这不是我想要的。

如果确实存在类似的东西,那将非常有用。我也对可能提出的任何替代方法持开放态度。提前感谢您提供的任何帮助。

3 个答案:

答案 0 :(得分:86)

如果你删除了两个字符,逗号和冒号,那么你的代码实际上有效的Python。

>>> gender= "male"
>>> print "At least, that's what %s told me." %("he" if gender == "male" else "she")
At least, that's what he told me.

更现代的风格使用.format,但是:

>>> s = "At least, that's what {pronoun} told me.".format(pronoun="he" if gender == "male" else "she")
>>> s
"At least, that's what he told me."

格式的参数可以是dict,无论你喜欢什么复杂,你都可以构建它。

答案 1 :(得分:10)

Python中有一个条件表达式,其格式为

A if condition else B

通过省略两个字符,您的示例很容易变成有效的Python:

print ("At least, that's what %s told me." % 
       ("he" if gender == "male" else "she"))

我经常喜欢的另一种选择是使用字典:

pronouns = {"female": "she", "male": "he"}
print "At least, that's what %s told me." % pronouns[gender]

答案 2 :(得分:4)

在Python 3.6+上,使用带有f"something"语句的formatted string literal(看起来像if):

print(f"Shut the door{'s' if num_doors > 1 else ''}.")

You can't use backslashes可以将f字符串中的引号转义,因此 您必须混合使用"'引号。