首页  >  文章  >  后端开发  >  Python 字符串中的 % 运算符有什么作用?

Python 字符串中的 % 运算符有什么作用?

Susan Sarandon
Susan Sarandon原创
2024-10-21 11:42:03547浏览

What Does the % Operator in Python Strings Do?

Python 的字符串格式化运算符 %

问题:% 运算符应用于字符串时的作用是什么Python?

答案: % 运算符用于 Python 中的字符串格式化。它允许您通过将值插入指定格式来创建格式化字符串。

基本语法为:

format % values

格式说明符字符串(format)包含占位符(%s,%d)等),值元组(values)包含要插入到这些占位符中的值。

例如:

<code class="python">name = "John"
age = 30

formatted_string = "Hi, I'm %s and I'm %d years old." % (name, age)
print(formatted_string)</code>

输出:

Hi, I'm John and I'm 30 years old.

在此示例中,%s 占位符替换为 name 变量的值,%d 占位符替换为age 变量的值。

以上是Python 字符串中的 % 运算符有什么作用?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn