用python打印变量和字符串

2024-04-20 12:09:05 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我知道如何打印变量和字符串。但是我怎样才能打印“我的字符串”card.price(它是我的变量)。我是说,这是我的代码: print "I have " (and here I would like to print my variable card.price)


Tags: andto字符串代码heremyhavecard
3条回答

这里(令人惊讶的)没有提到的是简单的连接。

示例:

foo = "seven"

print("She lives with " + foo + " small men")

结果:

She lives with seven small men

此外,从Python 3开始,不推荐使用%方法。别用那个。

假设您使用Python2.7(而不是3):

print "I have", card.price(如上所述)。

print "I have %s" % card.price(使用string formatting

print " ".join(map(str, ["I have", card.price]))(通过加入列表)

实际上,有很多方法可以做到这一点。我想要第二个。

通过打印由逗号分隔的多个值:

print "I have", card.price

print statement将输出由空格分隔的每个表达式,后跟一个换行符。

如果需要更复杂的格式,请使用^{} method

print "I have: {0.price}".format(card)

或者使用旧的和半弃用的^{} string formatting operator

相关问题 更多 >