Geo*_*eil 64 python string-formatting
我一直在用Python编写基于文本的游戏,我遇到过一个实例,我希望根据一组条件对字符串进行不同的格式化.
具体来说,我想显示描述房间内物品的文字.我希望在房间的描述中显示这个,当且仅当有问题的物品对象位于房间对象的物品清单中时.它的设置方式,我觉得简单地连接基于条件的字符串将不会按我的意愿输出,并且最好为每种情况设置不同的字符串.
我的问题是,是否有基于布尔条件结果格式化字符串的pythonic方法?我可以使用for循环结构,但我想知道是否有更简单的东西,类似于生成器表达式.
我正在寻找类似于此的东西,以字符串形式
num = [x for x in xrange(1,100) if x % 10 == 0]
Run Code Online (Sandbox Code Playgroud)
作为我的意思的一般例子:
print "At least, that's what %s told me." %("he" if gender == "male", else: "she")
Run Code Online (Sandbox Code Playgroud)
我意识到这个例子不是有效的Python,但它总体上显示了我正在寻找的东西.我想知道布尔字符串格式是否有任何有效的表达式,类似于上面的.在搜索了一下之后,我无法找到任何与条件字符串格式有关的内容.我确实在格式字符串上找到了几个帖子,但这不是我想要的.
如果确实存在类似的东西,那将非常有用.我也对可能提出的任何替代方法持开放态度.提前感谢您提供的任何帮助.
DSM*_*DSM 96
如果你删除两个字符,逗号和冒号,你的代码实际上是有效的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.
Run Code Online (Sandbox Code Playgroud)
但更现代的风格用途.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."
Run Code Online (Sandbox Code Playgroud)
格式化的参数可以是dict您构建的任何复杂性.
Sve*_*ach 12
Python中有一个条件表达式,它采用了这种形式
A if condition else B
Run Code Online (Sandbox Code Playgroud)
通过省略两个字符,您的示例很容易变成有效的Python:
print ("At least, that's what %s told me." %
("he" if gender == "male" else "she"))
Run Code Online (Sandbox Code Playgroud)
我经常喜欢的另一种选择是使用字典:
pronouns = {"female": "she", "male": "he"}
print "At least, that's what %s told me." % pronouns[gender]
Run Code Online (Sandbox Code Playgroud)
在Python 3.6+上,使用带格式的字符串文字(它们称为f-strings:f"{2+2}"produces "4")和以下if语句:
print(f"Shut the door{'s' if num_doors > 1 else ''}.")
Run Code Online (Sandbox Code Playgroud)
您不能在F字符串的表达式部分中使用反斜杠来转义引号,因此必须混合使用双引号"和单'引号。(您仍然可以在f字符串的外部使用反斜杠,例如f'{2}\n'可以)
| 归档时间: |
|
| 查看次数: |
53346 次 |
| 最近记录: |