How to implement conditional string formatting?

后端 未结 3 1859
花落未央
花落未央 2020-11-30 01:04

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.

Speci

相关标签:
3条回答
  • 2020-11-30 01:23

    On Python 3.6+, use a formatted string literal (they're called f-strings: f"{2+2}" produces "4") with an if statement:

    print(f"Shut the door{'s' if abs(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. (You can still use backslashes in the outer part of an f-string, eg. f'{2}\n' is fine)

    0 讨论(0)
  • 2020-11-30 01:25

    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]
    
    0 讨论(0)
  • 2020-11-30 01:37

    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.

    0 讨论(0)
提交回复
热议问题