在字符串中嵌入条件

时间:2015-02-25 02:10:14

标签: python string

这就是我想要做的 一个例子

Dogwood = TRUE
Wetdog = 'wet dog'
drydog = 'dog'
s = 'I see a ', Wetdog if dog wet else drydog
print(s)
# which does not work...is there a way to make it work?

#However this works
print('I see a ', Wetdog if dogwet else drydog)

我希望同样的东西可以工作但是在变量字符串中可以在需要时打印。

3 个答案:

答案 0 :(得分:2)

为了将条件的内容分配给字符串,您可以使用下面显示的格式。有关此问题的更多说明,请访问Conditional Expression

我在上面的代码中看不到dogwet。假设它们存在,并且它们是这样的......

dog = False #initial state of the dog
wet = True #state of a wet dog

然后下面的代码就可以了。

s = 'I see a {}'.format(Wetdog) if dog == wet else 'I see a {}'.format(drydog)

答案 1 :(得分:0)

您可以使用字符串连接(+运算符):

s = 'I see a ' + (Wetdog if dogwet else drydog)

答案 2 :(得分:0)

你能做的就是做这样的事情:

Wetdog = 'wet dog'
drydog = 'dog'

dogiswet = True;  #can be True or False depending on what you want it to be
dogisdry = True;  #can be True or False depending on what you want it to be

if dogiswet:
  print "I see a %s." % Wetdog

if dogisdry:
  print "I see a %s." % drydog