Python中操作符“%“基础用法


包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】!

在Python中,%运算符被用于字符串格式化,这种操作符允许你将指定的值插入到字符串中的占位符位置。格式化字符串的语法如下:
result = "string_template % value"
在这个结构中,string_template 是一个包含占位符的字符串,而 value 是可以被插入占位符的值。占位符由一个或多个字符组成,通常放在字符串中的 % 符号后面。

常用占位符类型

% 操作符的工作原理是通过在字符串中使用 % 符号作为占位符,然后通过 % 操作符将变量的值替换到这些占位符中。
占位符可以是以下几种类型:
  • %s:字符串(或任何可被转换成字符串的类型
  • %d 或 %i:整数
  • %f:浮点数
  • %x 或 %X:十六进制数
  • %o:八进制数
  • %%:字面上的 % 符号
占位符可以包含数字和标志,如:
  • %[+]:显示正负号
  • %[-]:左对齐
  • %[#]:交替格式
  • %[0]:填充零
  • %[width]:宽度
  • %[.precision]:精度(浮点数小数点后的位数)
本文给出一些案例,学习完这些案例,大家能很快熟悉%的基础用法。

在这里插入图片描述

1.基本字符串格式化
name = "Alice"
message = "Hello, %s" % name
print(message)  # "Hello, Alice"

在这里插入图片描述

2.整数格式化
age = 30
message = "I am %d years old" % age
print(message)  # "I am 30 years old"

在这里插入图片描述

3.浮点数格式化
price = 19.99
message = "The price is %f dollars" % price
print(message)  # "The price is 19.990000 dollars"

在这里插入图片描述

4.格式化正负号
balance = -100
message = "Your balance is %+d dollars" % balance
print(message) 

在这里插入图片描述

5.左对齐
message = "%-10s" % "left"
print(message)  # "left"

在这里插入图片描述

6.填充零
message = "%010d" % 5
print(message)  # "0000000005"

在这里插入图片描述

7.指定宽度和精度
message = "%6.2f" % 3.1415926
print(message)  # "   3.14"

在这里插入图片描述

8.格式化字典
person = {
    
    "name": "Bob", "age": 25}
message = "%(name)s is %(age)d years old" % person
print(message)  # "Bob is 25 years old"

在这里插入图片描述

9.多变量格式化
name = "Alice"
age = 30
message = "%s is %d years old" % (name, age)
print(message)  # "Alice is 30 years old"

在这里插入图片描述

10.格式化时区时间
from datetime import datetime
message = "The time is %s" % datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(message)

在这里插入图片描述

11.格式化时区时间带时区
import pytz
message = "The time in UTC is %s" % 
datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S')
print(message)
12.格式化复杂表达式
a, b = 10, 3
message = "The result of %d %% %d is %d" % (a, b, a % b)
print(message)  # "The result of 10 % 3 is 1"

在这里插入图片描述

13.格式化字符串中包含%符号
message = "A literal %% is %%%%"
print(message)  

在这里插入图片描述

以上这些案例展示了如何使用不同的占位符和格式化选项来生成各种类型的字符串。通过这种方式,可以创建定制化的字符串,以适应不同的应用场景。

图片

总结

  • 最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!

文末福利

  • 最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】领取!
  • ① Python所有方向的学习路线图,清楚各个方向要学什么东西
  • ② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
  • ③ 100多个Python实战案例,学习不再是只会理论
  • ④ 华为出品独家Python漫画教程,手机也能学习

可以扫描下方二维码领取【保证100%免费在这里插入图片描述