Python 在字符串中嵌入条件

Python 在字符串中嵌入条件,python,string,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) 我希望同样的东

这就是我想做的 一个例子

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)

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

为了将条件的内容分配给字符串,可以使用如下所示的格式。更多的解释可以在这里找到

我在上面的代码中没有看到
dog
wet
。假设它们存在,它们是这样的

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)

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


你可以这样做:

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

狗湿从哪里来或狗湿从哪里来?什么是
Dogwood=TRUE
?我认为有时代码只能是好的,因为如果它只是一个格式错误,代码是自解释的。。。尽管如此,我已经更新了我的答案。你也有一些不存在的变量,但是同样的,答案也不存在OP@PadraicCunningham他们在原始问题的来源列表中谁是“我们”,kemosabe?就个人而言,我鼓励人们在想要连接字符串时使用字符串连接——为什么你认为它在Python中适用?我更关心的是,
dogwet
似乎不存在于code@PadraicCunningham当然OP意外地将该变量错误命名为神秘的
山茱萸
,然后又将其错误输入一次为
狗湿
,这会由于出现了错误的空格而导致
语法错误
。这两个问题都很明显,也很明显与“在字符串中嵌入条件”无关。我认为这个问题中没有任何明显的东西。
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