Skip to main content
 首页 » 编程设计

python之python 中的 % 运算符有什么用

2025年05月04日9pander-it

我在一些与字符串相关的 Python 代码中看到了 % 运算符,例如:

String = "Value: " % variable 

这是什么意思?它与使用有何不同:

String = "Value: " + variable 

请您参考如下方法:

它用于将值插入到包含 format specifications 的字符串中

string = "number is %d" % 1 

或

string = "float is %.3f" % 3.1425 

这与 C 中的 spintf 的工作方式类似

您可以通过两种方式插入多个值:

string = "number %d and float %f" % (1,3.1415) 
string = "number %(mynum)d and float %(myfloat)f" % {'mynum':1,'myfloat':3.1415}