“string%variables”中的%运算符是什么?

2024-05-21 02:39:00 发布

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

我以为%(modulo)从除法返回了余数,但看到了这段代码,现在我感到困惑。你知道吗

代码如下:

prices = {
    "banana" : 4,
    "apple" : 2,
    "orange" : 1.5,
    "pear" : 3
}

stock = {
    "banana" : 6,
    "apple" : 0,
    "orange" : 32,
    "pear" : 15
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]

我的问题是关于最后三行的。%在这里做什么?你知道吗


Tags: key代码inappleforstockpricebanana
2条回答

这是旧的字符串格式化运算符,用于将字典的值添加到要打印的字符串中。你知道吗

你可以在docs上阅读更多关于它的信息。你知道吗

示例用法是

var = 10
var2 = 25.234
str_to_print = "The value of var is %d and of var2 is %0.2f" % (var, var2)

这里有很多例子和有用的信息https://pyformat.info/

这类似于Cprintf格式。参考若昂阿尔梅达的文件

相关问题 更多 >