Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

python - How to implement conditional string formatting?

I've been working on a text-based game in Python, and I've come across an instance where I want to format a string differently based on a set of conditions.

Specifically, I want to display text describing items in a room. I want this to be displayed, in the room's description, if and only if the item object in question is in the room object's list of items. The way it is set up, I feel that simply concatenating strings based on conditionals will not output as I want, and it would be better to have a different string for each case.

My question is, is there any pythonic method for formatting strings based on the result of a Boolean conditional? I could use a for loop structure, but I was wondering if there was something easier, similar to a generator expression.

I'm looking for something similar to this, in string form

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

As a general example of what I mean:

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

I realize that this example is not valid Python, but it shows, in general, what I'm looking for. I'm wondering if there is any valid expression for boolean string formatting, similar to the above. After searching around a bit, I was unable to find anything pertaining specifically to conditional string formatting. I did find several posts on format strings in general, but that is not what I'm looking for.

If something like that does indeed exist, it would be very useful. I'm also open to any alternate methods that may be suggested. Thanks in advance for any help you can provide.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code actually is valid Python if you remove two characters, the comma and the colon.

>>> 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.

More modern style uses .format, though:

>>> 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."

where the argument to format can be a dict you build in whatever complexity you like.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...