打印方法问题Python

时间:2009-02-09 21:39:50

标签: python string

在python中,第二个%表示什么?

print "%s" % ( i )

5 个答案:

答案 0 :(得分:8)

正如其他人所说,这是Python字符串格式化/插值运算符。它基本上相当于C中的sprintf,例如:

a = "%d bottles of %s on the wall" % (10, "beer")

等同于

a = sprintf("%d bottles of %s on the wall", 10, "beer");

in C.其中每个都有a设置为"10 bottles of beer on the wall"

的结果

但请注意,Python 3.0中不推荐使用此语法;它的替换看起来像

a = "{0} bottles of {1} on the wall".format(10, "beer")

这是有效的,因为任何字符串文字都会被Python自动转换为str对象。

答案 1 :(得分:5)

第二个%是字符串插值运算符。

Link to documentation

答案 2 :(得分:0)

这是format specifier

简单用法:

# Prints: 0 1 2 3 4 5 6 7 8 9
for i in range(10):
    print "%d" % i,

答案 3 :(得分:0)

print "%d%s" % (100, "trillion dollars") # outputs: 100 trillion dollars

答案 4 :(得分:0)

如果您要将代码翻译成英语,则会说: string i 并将其格式化为谓词字符串。

另一个例子:

name = "world"
print "hello, %s" % (name)

More information about format specifiers.