Python中的format()函数用于格式化字符串。它可以将不同类型的数据格式化为字符串中指定的格式。以下是format()函数的各种用法及示例:

"{<参数序号>:<格式控制标记>}".format()

格式内容:

<.精度>-后面可以加<类型>

<类型>

整数类型:b--2进制、c--Unicode、d--十进制、o--八进制、x/X--十六进制

浮点数类型:

  • e/E--以科学计数法的形式输出浮点数
  • f--以浮点数的形式输出浮点数。默认情况下,会输出小数点后面六位数字,但是可以通过指定精度来控制输出的位数
  • %:--以百分数的形式输出浮点数,乘以100并在末尾加上百分号。
  • s--输出字符串
  • r--输出字符串的repr()形式(原始字符串)

1、位置参数

这是最基本的用法,可以将格式化字符串中的占位符{}替换为相应的位置参数。

name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# 输出:My name is John and I am 30 years old.

2、命名参数

可以使用命名参数来指定占位符的值,这样可以使代码更易读

print("My name is {name} and I am {age} years old.".format(name="John", age=30))
# 输出:My name is John and I am 30 years old.

3、位置参数与命名参数的混合使用

位置参数和命名参数可以混合使用,但是位置参数必须在前面。

print("My name is {0} and I am {1} years old. My hobby is {hobby}.".format("John", 30, hobby="swimming"))
# 输出:My name is John and I am 30 years old. My hobby is swimming.

4、使用字典格式化字符串

可以使用字典的键值对来格式化字符串,使用{}包含键名,键名在format()函数中指定。

person = {'name': 'John', 'age': 30}
print("My name is {name} and I am {age} years old.".format(**person))
# 输出:My name is John and I am 30 years old.

5、格式化数字

可以使用占位符指定数字的格式,例如{:d}表示整数,{:f}表示浮点数。

num = 3.14159
print("The value of pi is approximately {:.2f}.".format(num))
# 输出:The value of pi is approximately 3.14.

6、格式化时间

可以使用strftime()函数指定时间的格式,然后在格式化字符串中使用占位符替换时间。

from datetime import datetime
now = datetime.now()
print("Today is {:%Y-%m-%d %H:%M:%S}.".format(now))
# 输出:Today is 2023-04-19 18:30:00.

7、使用格式字符串语法

Python 3.6及以上版本支持使用f-strings(格式化字符串字面值)来格式化字符串,用法比较简单,直接在字符串前面加上字母“f”,然后使用花括号{}包含变量名。

name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
# 输出:My name is John and I am 30 years old.

8、格式化二进制、八进制和十六进制数字

可以使用占位符指定数字的进制,例如{:b}表示二进制,{:o}表示八进制,{:x}表示十六进制。

num = 42
print("The binary representation of 42 is {:b}.".format(num))
# 输出:The binary representation of 42 is 101010.print("The octal representation of 42 is {:o}.".format(num))
# 输出:The octal representation of 42 is 52.print("The hexadecimal representation of 42 is {:x}.".format(num))
# 输出:The hexadecimal representation of 42 is 2a.

9.格式化货币

可以使用占位符指定货币符号和小数点的位置,例如{:,.2f}表示保留两位小数,以逗号分隔千位,使用美元符号。

price = 123456.789
print("The price is ${:,.2f}.".format(price))
# 输出:The price is $123,456.79.

10、格式化百分比

可以使用占位符将小数转换为百分比,例如{:.2%}表示保留两位小数,乘以100并添加百分号。

ratio = 0.5678
print("The ratio is {:.2%}.".format(ratio))
# 输出:The ratio is 56.78%.

11、当需要控制字符串的宽度时,可以使用占位符指定输出的字符宽度

name = "Alice"
print("Hello, {:10}!".format(name))
# 输出:Hello, Alice     !print("Hello, {:^10}!".format(name))
# 输出:Hello,   Alice   !print("Hello, {:<10}!".format(name))
# 输出:Hello, Alice     !print("Hello, {:>10}!".format(name))
# 输出:Hello,      Alice!

12、如果要将字符长度作为变量传递给格式化字符串的宽度字段,可以使用f-string(格式化字符串字面值)。

width = 10
i = 42
formatted_string = f"{i:^{width}}"
print(formatted_string)

或者

width = 10
i = 42
formatted_string = "{:^{}}".format(i, width)
print(formatted_string)

format()函数的用法相关推荐

  1. Format函数的用法

    Format函数的用法 转载 格式指令具有以下的形式: "%" [index ":"] ["-"] [width] [".&quo ...

  2. python Format()函数的用法___实例详解(一)(全,例多)___各种格式化替换,format对齐打印

    python Format()函数的用法___实例详解(一)(全,例多) (格式化替换,关键字替换,列表字典替换,类格式化, 魔法函数格式化,对齐及填充格式化,format对齐打印) 本篇目录内容:

  3. python的format函数的用法及实例

    目录 1.format函数的语法及用法 (1)语法:'{}'.format() (2)用法:用于格式化字符串.可以接受无限个参数,可以指定顺序.返回结果为字符串. 2.实例 (1)不设置位置,按默认顺 ...

  4. c语言函数参数类型格式化,格式化输出的几种方法 主要介绍format函数的用法

    1 str自带函数格式化输出 rjust() ljust() center() zfill() zfill是补齐零 介绍: rjust(...) S.rjust(width[, fillchar]) ...

  5. format函数基本用法

    1.format函数基本格式:<模块字符>.format(<逗号分隔的参数>) 例如: print("{},我想跟你说:{}".format(a,b)) 2 ...

  6. Python format函数的用法详解

    1.通过位置来填充字符串 print('hello {0} i am {1}'.format('world','python')) # 输入结果:hello world i am python pri ...

  7. Python中Print()函数的用法___实例详解(二)(全,例多)

    Python中Print()函数的用法___实例详解(二)(全,例多) 目录 十一.Print()小例子 十二.Print()中文输入显示乱码问题 十三.Print()写入文件 十四.print()在 ...

  8. format函数python的顺序_[转载] Python中format函数用法

    Python中format函数用法 format优点 format是python2.6新增的格式化字符串的方法,相对于老版的%格式方法,它有很多优点. 1.不需要理会数据类型的问题,在%方法中%s只能 ...

  9. Format函数用法

    function Format(const Format: string; const Args: array of const): string; $[SysUtils.pas 功能 返回按指定方式 ...

  10. Delphi Format函数功能及用法详解

    DELPHI中Format函数功能及用法详解 DELPHI中Format函数功能及用法详解function Format(const Format: string; const Args: array ...

最新文章

  1. 利用Word将连着一起的字符按照自己指定的”字符串或者字换行“自动换行。
  2. 裁剪图像周围空白区域_零基础PS纠正倾斜的图像效果
  3. 160 - 31 cracking4all.2
  4. php获取当前页面数据,ThinkPHP如何获取当前页面URL信息?
  5. 基于Spring Security的认证方式_实现认证功能_Spring Security OAuth2.0认证授权---springcloud工作笔记120
  6. BIO,Socket网络编程入门代码示例,NIO网络编程入门代码示例,AIO 网络编程
  7. Shanda EZ Mini
  8. 201771010111李瑞红《第十六周学习总结》
  9. Mac下CUDA开启及Tensorflow-gpu 1.4 安装
  10. Python 基础语法
  11. Go语言学习之go环境搭建
  12. 台式计算机硬盘序号,[硬盘序列号的查看方法]台式机查看序列号的方法
  13. wav怎么转换成mp3?步骤详细介绍
  14. 2021-10-26
  15. 论文阅读17 | Cross-modality Person re-identification with Shared-Specific Feature Transfer
  16. git clone报错Could not resolve proxy : proxy-szn
  17. 计算机里硬盘图标,两妙方轻松更改电脑硬盘盘符的图标
  18. 计算机排名2018全国,2018全国90所计算机专业大学排名,分为ABC三个等级
  19. nagios通过python获取ESXi硬盘SMART信息
  20. Java图像处理--------RGB调色面板

热门文章

  1. 解决MPS运行中出现Unsupported major.minor version错误问题
  2. 《算法图解-像小说一样有趣的算法入门书》最全读书笔记--Binrry(冰蕊)
  3. 工厂如何提升生产环境管理水平?动环监控排第几
  4. ElementUI v2.15.0 使用手册
  5. 浩顺AC671指纹考勤机二次开发(demo)
  6. java多线程电梯调度_面向对象之多线程(可捎带电梯调度)
  7. hot~《国家网络安全应急预案》你知道么。
  8. 【苹果推群发】苹果相册推广告协议应用程序将被发送到服务器
  9. 计算机数据交换技术发展的顺序,计算机网络数据交换技术的发展探析
  10. 一个自动将状态机生成代码的软件