【七种常见的字符串格式化方法】

【七种常见的字符串格式化方法】

参考链接: 七种常见的字符串格式化方法

1、保留小数点后两位

>>>print("{:.2f}".format(3.1415))

3.14

2、带符号保留小数点后两位

>>>print("{:+.2f}".format(-3.1415))

-3.14

3、不带小数点

>>>print("{:.0f}".format(2.7))

3

4、整数补零,填充左边, 宽度为3

>>>print("{:0>3d}".format(6))

006

5、以逗号分隔的数字格式

>>>print("{:,}".format(123456789))

123,456,789

6、百分比格式

>>>print("{:.2%}".format(0.94545))    # 百分比小数点后两位

94.55%

7、指数记法

>>>print("{:.2e}".format(123456789))   #科学计数法,小数点后两位

1.23e+08

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,字符串格式化是通过将变量的值插入到字符串中来创建新字符串的过程。以下是几种常见字符串格式化方法: 1. 使用占位符 在字符串中使用占位符(例如%s和%d)来表示变量的值,然后通过字符串的format()方法将这些占位符替换为实际的值。例如: ``` name = "Alice" age = 30 print("My name is %s and I am %d years old." % (name, age)) ``` 输出结果为: My name is Alice and I am 30 years old. 2. 使用f-strings f-strings是Python 3.6及更高版本引入的一种格式化字符串方法。它们允许在字符串中嵌入表达式,并在字符串中使用大括号{}表示变量的值。例如: ``` name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.") ``` 输出结果为: My name is Alice and I am 30 years old. 3. 使用format()方法 format()方法可以接受任意数量的参数,并使用花括号{}来表示变量的值。例如: ``` name = "Alice" age = 30 print("My name is {} and I am {} years old.".format(name, age)) ``` 输出结果为: My name is Alice and I am 30 years old. 4. 使用模板字符串 模板字符串是一种包含占位符的字符串,可以使用字符串模板库(Template)中的substitute()方法将占位符替换为实际的值。例如: ``` from string import Template name = "Alice" age = 30 template = Template("My name is $name and I am $age years old.") print(template.substitute(name=name, age=age)) ``` 输出结果为: My name is Alice and I am 30 years old.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值