Python格式化字符串常量f-string总结

本文主要总结在Python中如何使用格式化字符串常量f-string(Formatted string literals)。在 Python 程序中,大部分时间都是使用 %s 或 format 来格式化字符串,在 Python 3.6 中新的选择 f-string可以用于格式化字符串。相比于其他字符串格式方式,f-string更快,更易读,更简明且不易出错。f-string通过f或 F 修饰字符串,如f’xxx’ 或 F’xxx’),以大括号 {}表示被替换的字段。对齐的格式在冒号后指定;例如:f’{price:.3},其中price是变量名。

1 语法

1.1 Python字符串格式

以下示例总结了Python中的字符串格式设置选项。

name = 'Peter'
age = 23 print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')
Peter is 23 years old
Peter is 23 years old
Peter is 23 years old

这个是最古老的方式,通过%代替变量,如下所示:

print(’%s is %d years old’ % (name, age))

从Python 3.0开始,format()引入了该功能以提供高级格式化选项。如下所示:

print(’{} is {} years old’.format(name, age))

从Python 3.6开始,Python f-string用于格式化变量,如下所示:

print(f’{name} is {age} years old’)

1.2 Python f-string中使用表达式

我们可以将表达式放在{}方括号之间,如下所示:

bags = 3
apples_in_bag = 12 # 对f-string中的表达式求值
print(f'There are total of {bags * apples_in_bag} apples')
There are total of 36 apples

1.3 Python f-string中使用字典

user = {'name': 'John Doe', 'occupation': 'gardener'}

# 获得对应的值
print(f"{user['name']} is a {user['occupation']}")
John Doe is a gardener

1.4 Python多行f-string

def mymax(x, y):

    return x if x > y else y

a = 3
b = 4 print(f'Max of {a} and {b} is {mymax(a, b)}')
Max of 3 and 4 is 4

1.5 Python f-string对象

Python f-string也接受对象;这些对象必须定义有__str__()或__repr__()函数。

class User:
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation def __repr__(self):
return f"{self.name} is a {self.occupation}" u = User('John Doe', 'gardener') print(f'{u}')
John Doe is a gardener

1.6 Python f-string中转义字符

为了转义{},我们将嵌入{{}}转义。单引号用反斜杠字符转义。如下所示:

print(f'Python uses {{}} to evaludate variables in f-strings')
print(f'This was a \'great\' film')
Python uses {} to evaludate variables in f-strings
This was a 'great' film

1.7 Python f-string中格式化 datetime

示例显示格式化的当前日期时间。日期时间格式说明符跟在:字符后面

import datetime

now = datetime.datetime.now()

print(f'{now:%Y-%m-%d %H:%M}')
2020-06-17 20:39

1.8 Python f-string中格式化 floats

浮点值带有f后缀。我们还可以指定精度:小数位数。精度通过.后的值设定。例如.2f表示浮点数值,小数点后保留两位小时。如下所示输出两位和五位小数位数:

val = 12.3

print(f'{val:.2f}')
print(f'{val:.5f}')
12.30
12.30000

1.9 Python f-string中字符宽度

字符宽度说明符设置值的宽度。如果该值短于指定的宽度,则该值可以用空格或其他字符填充。如下程序所示打印三列。每个列都有一个预定义的宽度。第一列使用0填充较短的值,如果不填默认使用空格填充。

for x in range(1, 11):
print(f'{x:02} {x*x:3} {x*x*x:4}')
01   1    1
02 4 8
03 9 27
04 16 64
05 25 125
06 36 216
07 49 343
08 64 512
09 81 729
10 100 1000

1.10 Python f-string对齐字符串

默认情况下,字符串左对齐。我们可以使用>字符将字符串向右对齐。>字符跟在冒号字符后面。如下所示我们有四根不同长度的字符串。我们将输出的宽度设置为10个字符。这些值向右对齐。

s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd' print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')
         a
ab
abc
abcd

1.11 Python f-string中进制表示

数字可以具有各种进制,例如十进制或十六进制。

# hexadecimal
print(f"{a:x}") # octal
print(f"{a:o}") # scientific
print(f"{a:e}")
3
3
3.000000e+00

2 参考

http://zetcode.com/python/fstring/

https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals

最新文章

  1. 如何在mac上用终端打开XAMPP自带的MySQL
  2. Python 获得对象内存占用内存大小 sys.getsizeof
  3. vim 使用2 转载 为了打开方便
  4. Python核心编程笔记(类)
  5. js 对象与函数的区别
  6. .NET打印功能实现 PrintDocument
  7. 在别的地方看的<<给程序员介绍一些C++开源库>>,记录给大家共同学习
  8. spring-bean属性配置解析
  9. 【转】CXF+Spring+Eclipse简明示例
  10. 总结随笔(Beta)
  11. [Codeforces 864F]Cities Excursions
  12. Ceres-Solver库入门
  13. numpy中stack、hstack,vstack,dstack函数功能解释
  14. 屏蔽右键+f12
  15. ubuntu14安装node0.12.7
  16. BATJ等大厂最全经典面试题分享
  17. (转)Linux中设置服务自启动的三种方式
  18. sql语句之from子句
  19. EZ 2018 1 21 2018noip第五次膜你赛
  20. Java知识回顾 (3)运算符

热门文章

  1. Vue3解决ElementPlus Drawer或弹出对话框不生效的问题
  2. MySQL之安装(linux两种版本版本安装)
  3. C语言之走迷宫深度和广度优先(利用堆栈和队列)
  4. 线性表的基本操作(C语言实现)
  5. 上传数据、下载模板文件解决方案(前端:antd;后端:.Net Core WebAPI)
  6. 十五、资源控制之Deployment
  7. day03-CSS
  8. Java安全之Tomcat6 Filter内存马
  9. Flutter 构建windows应用
  10. java学习之Servlet