ChatGPT解决这个技术问题 Extra ChatGPT

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.

if you remove the comma and the semicolon it becomes valid python

p
phoenix

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.


s = "At least, that's what {pronoun} told me.".format(pronoun=["she","he"][gender == "male"])
Is it possible to squeeze an elif in here? e.g. format(pronoun="he" if gender == "male" pronoun = "she" elif gender=="female" else "not found")
The answer works for only one if else statement when I added ("/{tech}".format(tech='w' if portfolio=='onshore' else 's' if portfolio=='solar'), I get invalidSyntax Error
@HVS it is possible, see this answer on stringing together else/if statements to simulate an inline elif. But you really shouldn't, you should define a function instead.
B
Boris Verkhovskiy

On Python 3.6+, use an f-string with a conditional expression (a one-line version of the if/else statement):

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

You can't use backslashes to escape quotes in the expression part of an f-string so you have to mix double " and single ' quotes. To be clear, you can still use backslashes in the outer part of an f-string, so f'{2+2}\n' is fine.


Great, but what if 's' is a variable ?
@AhmedHussein then you pass the variable print(f"Shut the door{my_variable if num_doors > 1 else ''}.")
I had to figure this one out for myself - it seems that as you are making this a conditional value that you MUST have the else clause to define a default value!
@DavidW. right, this is called the ternary operator (also see PEP 308) and I'm not aware of any language that lets you omit either result. You'd have to evaluate the left hand side even if the if was False to determine what type the default should be.
m
martineau

There is a conditional expression in Python which takes the form:

A if condition else B

Your example can easily be turned into valid Python by omitting just two characters:

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

An alternative I'd often prefer is to use a dictionary:

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