How to implement conditional string formatting?

后端 未结 3 1874
花落未央
花落未央 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: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]
    

提交回复
热议问题