• 【Python简明教程三十(完结)】字符串格式化


    本节为简明教程的完结篇。为了确保字符串按预期显示,我们可以使用 format() 方法对结果进行格式化。

    1 字符串format()

    format()方法允许您格式化字符串的选定部分。

    有时文本的一部分是你无法控制的,也许它们来自数据库或用户输入?

    要控制此类值,请在文本中添加占位符(花括号 {}),然后通过 format() 方法运行值:

    实例
    添加要显示价格的占位符:

    price = 52
    txt = "The price is {} dollars"
    print(txt.format(price))    # The price is 52 dollars
    
    • 1
    • 2
    • 3

    可以在花括号内添加参数以指定如何转换值:

    实例
    将价格格式化为带有两位小数的数字:

    txt = "The price is {:.2f} dollars"    # The price is 52.00 dollars
    
    • 1

    查看字符串 format() 参考手册中的所有格式类型。

    2 多个值

    如需使用更多值,只需向 format() 方法添加更多值:

    print(txt.format(price, itemno, count))
    
    • 1

    并添加更多占位符:

    实例

    quantity = 3
    itemno = 567
    price = 52
    myorder = "I want {} pieces of item number {} for {:.2f} dollars."
    print(myorder.format(quantity, itemno, price))  # I want 3 pieces of item number 567 for 52.00 dollars.
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3 索引号

    可以使用索引号(花括号 {0} 内的数字)来确保将值放在正确的占位符中:

    实例

    quantity = 3
    itemno = 567
    price = 52
    myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
    print(myorder.format(quantity, itemno, price))  # I want 3 pieces of item number 567 for 52.00 dollars.
    
    • 1
    • 2
    • 3
    • 4
    • 5

    此外,如果要多次引用相同的值,请使用索引号:

    实例

    age = 63
    name = "Bill"
    txt = "His name is {1}. {1} is {0} years old."
    print(txt.format(age, name))  # His name is Bill. Bill is 63 years old.
    
    • 1
    • 2
    • 3
    • 4

    4 命名索引

    还可以通过在花括号 {carname} 中输入名称来使用命名索引,但是在传递参数值 txt.format(carname = “Ford”) 时,必须使用名称:

    实例

    myorder = "I have a {carname}, it is a {model}."
    print(myorder.format(carname = "Porsche", model = "911"))  # I have a Porsche, it is a 911.
    
    • 1
    • 2

    本人独自运营了微信公众号,用于分享个人学习及工作生活趣事,大家可以关注一波。(微信搜索“微思研”)

  • 相关阅读:
    【总结】Idea 编译maven项目报错NoSuchMethodError DefaultModelValidator
    【JavaScript总结】双等与三等
    【数据结构与算法学习】散列表(Hash Table,哈希表)
    Win11如何关闭最近打开项目?Win11关闭最近打开项目的方法
    Redis 主从搭建和哨兵搭建
    Linux操作系统——类UNIX系统
    视频推拉流/直播点播平台EasyDSS分享的链接提示“无信号”,该如何解决?
    快速修改ppt | 显得不单调
    【前端】 响应式布局
    [附源码]java毕业设计哈金院食堂美食评价系统
  • 原文地址:https://blog.csdn.net/weixin_44237659/article/details/126595101