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

105 投票
3 回答
135935 浏览
提问于 2025-04-17 12:52

我最近在用Python做一个文字冒险游戏,遇到一个问题,就是我想根据一些条件来格式化字符串。

具体来说,我想在房间的描述中显示一些物品的信息。只有当某个物品在房间的物品列表里时,这段文字才会显示出来。现在的设置让我觉得,单纯地根据条件拼接字符串可能达不到我想要的效果,最好是为每种情况准备一个不同的字符串。

我想问问,有没有什么Python的方法可以根据布尔条件的结果来格式化字符串?我可以用循环结构来实现,但我在想有没有更简单的方法,像生成器表达式那样。

我想要的东西大概是这样的,字符串形式:

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 个回答

18

在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]
62

使用 f-string

plural = ''
if num_doors != 1:
    plural = 's'

print(f'Shut the door{plural}.')

或者可以用一行代码来写,使用 条件表达式(这是一种简化版的 if/else 语句):

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

需要注意的是,因为在 Python 3.12 之前,你不能在 f-string 的表达式部分使用反斜杠 \ 来转义引号,所以你必须混合使用双引号 " 和单引号 '。不过在 f-string 的外部部分,你仍然可以使用反斜杠,所以像 f'{2+2}\n' 这样的写法是可以的。

139

你的代码其实是有效的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."

在这里,传给format的参数可以是你自己构建的一个dict,可以根据需要复杂程度来设计。

撰写回答