ITPub博客

首页 > 数据库 > 数据库开发技术 > 一文介绍Python中操作符 % 基础用法

一文介绍Python中操作符 % 基础用法

原创 数据库开发技术 作者:derekwh 时间:2024-08-20 11:40:00 0 删除 编辑

在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"
  1. 整数格式化
    age = 30
    message = "I am %d years old" % age
    print(message)  # "I am 30 years old"
  1. 浮点数格式化
    price = 19.99
    message = "The price is %f dollars" % price
    print(message)  # "The price is 19.990000 dollars"
  1. 格式化正负号
    balance = -100
    message = "Your balance is %+d dollars" % balance
    print(message) 
  1. 左对齐
    message = "%-10s" % "left"
    print(message)  # "left        "
  1. 填充零
    message = "%010d" % 5
    print(message)  # "0000000005"
  1. 指定宽度和精度
    message = "%6.2f" % 3.1415926
    print(message)  # "   3.14"
  1. 格式化字典
    person = {"name": "Bob", "age": 25}
    message = "%(name)s is %(age)d years old" % person
    print(message)  # "Bob is 25 years old"
  1. 多变量格式化
    name = "Alice"
    age = 30
    message = "%s is %d years old" % (name, age)
    print(message)  # "Alice is 30 years old"
  1. 格式化时区时间
    from datetime import datetime
    message = "The time is %s" % datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(message)
  1. 格式化时区时间带时区

    import pytz
    message = "The time in UTC is %s" % datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S')
    print(message)
  2. 格式化复杂表达式

    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"
  1. 格式化字符串中包含%符号
    message = "A literal %% is %%%%"
    print(message)  

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



原文作者:Python学习杂记;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论
央企算法工程师,微信公众号: python数智工坊

注册时间:2021-03-14

  • 博文量
    305
  • 访问量
    162320