参考链接: Python | 字符串lower

简介 f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便。f-string在形式上是以 f 或 F 修饰符引领的字符串(f'xxx'或 F'xxx'),以大括号 {} 标明被替换的字段;f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式:

While other string literals always have a constant value, formatted strings are really expressions evaluated at run time. (与具有恒定值的其它字符串常量不同,格式化字符串实际上是运行时运算求值的表达式。) —— Python Documentation

f-string在功能方面不逊于传统的%-formatting语句和str.format()函数,同时性能又优于二者,且使用起来也更加简洁明了,因此对于Python3.6及以后的版本,推荐使用f-string进行字符串格式化。

用法 此部分内容主要参考以下资料:

Python Documentation – Formatted String Literals Python Documentation – Format String Syntax PEP 498 – Literal String Interpolation Python 3’s f-Strings: An Improved String Formatting Syntax (Guide) python3 f-string格式化字符串的高级用法 Python 3: An Intro to f-strings

简单使用 f-string用大括号 {} 表示被替换字段,其中直接填入替换内容:

>>> name = 'Eric'

>>> f'Hello, my name is {name}'

'Hello, my name is Eric'

>>> number = 7

>>> f'My lucky number is {number}'

'My lucky number is 7'

>>> price = 19.99

>>> f'The price of this book is {price}'

'The price of this book is 19.99'

表达式求值与函数调用 f-string的大括号 {} 可以填入表达式或调用函数,Python会求出其结果并填入返回的字符串内:

>>> f'A total number of {24 * 8 + 4}'

'A total number of 196'

>>> f'Complex number {(2 + 2j) / (2 - 3j)}'

'Complex number (-0.15384615384615388+0.7692307692307692j)'

>>> name = 'ERIC'

>>> f'My name is {name.lower()}'

'My name is eric'

>>> import math

>>> f'The answer is {math.log(math.pi)}'

'The answer is 1.1447298858494002'

引号、大括号与反斜杠 f-string大括号内所用的引号不能和大括号外的引号定界符冲突,可根据情况灵活切换 ' 和 ":

>>> f'I am {"Eric"}'

'I am Eric'

>>> f'I am {'Eric'}'

File "<stdin>", line 1

f'I am {'Eric'}'

^

SyntaxError: invalid syntax

若 ' 和 " 不足以满足要求,还可以使用 ''' 和 """:

>>> f"He said {"I'm Eric"}"

File "<stdin>", line 1

f"He said {"I'm Eric"}"

^

SyntaxError: invalid syntax

>>> f'He said {"I'm Eric"}'

File "<stdin>", line 1

f'He said {"I'm Eric"}'

^

SyntaxError: invalid syntax

>>> f"""He said {"I'm Eric"}"""

"He said I'm Eric"

>>> f'''He said {"I'm Eric"}'''

"He said I'm Eric"

大括号外的引号还可以使用 \ 转义,但大括号内不能使用 \ 转义:

>>> f'''He\'ll say {"I'm Eric"}'''

"He'll say I'm Eric"

>>> f'''He'll say {"I\'m Eric"}'''

File "<stdin>", line 1

SyntaxError: f-string expression part cannot include a backslash

f-string大括号外如果需要显示大括号,则应输入连续两个大括号 {{ 和 }}:

>>> f'5 {"{stars}"}'

'5 {stars}'

>>> f'{{5}} {"stars"}'

'{5} stars'

上面提到,f-string大括号内不能使用 \ 转义,事实上不仅如此,f-string大括号内根本就不允许出现 \。如果确实需要 \,则应首先将包含 \ 的内容用一个变量表示,再在f-string大括号内填入变量名:

>>> f"newline: {ord('\n')}"

File "<stdin>", line 1

SyntaxError: f-string expression part cannot include a backslash

>>> newline = ord('\n')

>>> f'newline: {newline}'

'newline: 10'

f-string还可用于多行字符串:

>>> name = 'Eric'

>>> age = 27

>>> f"Hello!" \

... f"I'm {name}." \

... f"I'm {age}."

"Hello!I'm Eric.I'm 27."

>>> f"""Hello!

... I'm {name}.

... I'm {age}."""

"Hello!\n I'm Eric.\n I'm 27."

自定义格式:对齐、宽度、符号、补零、精度、进制等 f-string采用 {content:format} 设置字符串格式,其中 content 是替换并填入字符串的内容,可以是变量、表达式或函数等,format是格式描述符。采用默认格式时不必指定 {:format},如上面例子所示只写 {content} 即可。

关于格式描述符的详细语法及含义可查阅Python官方文档,这里按使用时的先后顺序简要介绍常用格式描述符的含义与作用:

注1:0width 不可用于复数类型和非数值类型,width.precision 不可用于整数类型。  注2:width.precision 用于不同格式类型的浮点数、复数时的含义也不同:用于 f、F、e、E 和 % 时 precision 指定的是小数点后的位数,用于 g 和 G 时 precision 指定的是有效数字位数(小数点前位数+小数点后位数)。  注3:width.precision 除浮点数、复数外还可用于字符串,此时 precision 含义是只使用字符串中前 precision 位字符。

示例:

>>> a = 123.456

>>> f'a is {a:8.2f}'

'a is 123.46'

>>> f'a is {a:08.2f}'

'a is 00123.46'

>>> f'a is {a:8.2e}'

'a is 1.23e+02'

>>> f'a is {a:8.2%}'

'a is 12345.60%'

>>> f'a is {a:8.2g}'

'a is 1.2e+02'

>>> s = 'hello'

>>> f's is {s:8s}'

's is hello '

>>> f's is {s:8.3s}'

's is hel '

>>> a = 1234567890.098765

>>> f'a is {a:f}'

'a is 1234567890.098765'

>>> f'a is {a:,f}'

'a is 1,234,567,890.098765'

>>> f'a is {a:_f}'

'a is 1_234_567_890.098765'

>>> b = 1234567890

>>> f'b is {b:_b}'

'b is 100_1001_1001_0110_0000_0010_1101_0010'

>>> f'b is {b:_o}'

'b is 111_4540_1322'

>>> f'b is {b:_d}'

'b is 1_234_567_890'

>>> f'b is {b:_x}'

'b is 4996_02d2'

>>> a = 1234

>>> f'a is {a:^#10X}'      # 居中,宽度10位,十六进制整数(大写字母),显示0X前缀

'a is   0X4D2   '

>>> b = 1234.5678

>>> f'b is {b:<+10.2f}'    # 左对齐,宽度10位,显示正号(+),定点数格式,2位小数

'b is +1234.57  '

>>> c = 12345678

>>> f'c is {c:015,d}'      # 高位补零,宽度15位,十进制整数,使用,作为千分分割位

'c is 000,012,345,678'

>>> d = 0.5 + 2.5j

>>> f'd is {d:30.3e}'      # 宽度30位,科学计数法,3位小数

'd is           5.000e-01+2.500e+00j'

>>> import datetime

>>> e = datetime.datetime.today()

>>> f'the time is {e:%Y-%m-%d (%a) %H:%M:%S}'   # datetime时间格式

'the time is 2018-07-14 (Sat) 20:46:02'

lambda表达式

f-string大括号内也可填入lambda表达式,但lambda表达式的 : 会被f-string误认为是表达式与格式描述符之间的分隔符,为避免歧义,需要将lambda表达式置于括号 () 内:

>>> f'result is {lambda x: x ** 2 + 1 (2)}'

File "<fstring>", line 1

(lambda x)

^

SyntaxError: unexpected EOF while parsing

>>> f'result is {(lambda x: x ** 2 + 1) (2)}'

'result is 5'

>>> f'result is {(lambda x: x ** 2 + 1) (2):<+7.2f}'

综合示例

>>> a = 1234

>>> f'a is {a:^#10X}' # 居中,宽度10位,十六进制整数(大写字母),显示0X前缀

'a is 0X4D2 '

>>> b = 1234.5678

>>> f'b is {b:<+10.2f}' # 左对齐,宽度10位,显示正号(+),定点数格式,2位小数

'b is +1234.57 '

>>> c = 12345678

>>> f'c is {c:015,d}' # 高位补零,宽度15位,十进制整数,使用,作为千分分割位

'c is 000,012,345,678'

>>> d = 0.5 + 2.5j

>>> f'd is {d:30.3e}' # 宽度30位,科学计数法,3位小数

'd is 5.000e-01+2.500e+00j'

>>> import datetime

>>> e = datetime.datetime.today()

>>> f'the time is {e:%Y-%m-%d (%a) %H:%M:%S}' # datetime时间格式

'the time is 2018-07-14 (Sat) 20:46:02'

lambda表达式

f-string大括号内也可填入lambda表达式,但lambda表达式的 : 会被f-string误认为是表达式与格式描述符之间的分隔符,为避免歧义,需要将lambda表达式置于括号 () 内:

>>> f'result is {lambda x: x ** 2 + 1 (2)}'

File "<fstring>", line 1

(lambda x)

^

SyntaxError: unexpected EOF while parsing

>>> f'result is {(lambda x: x ** 2 + 1) (2)}'

'result is 5'

>>> f'result is {(lambda x: x ** 2 + 1) (2):<+7.2f}'

[转载] python3 格式化字符串 f-string 介绍相关推荐

  1. python3 格式化字符串 f-string 介绍

    简介 f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal S ...

  2. python: 格式化字符串f()用法

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/sunxb10/article/deta ...

  3. python 字符串 f_Python格式化字符串(f,F,format,%)

    # 格式化字符串: 在字符串前加上 f 或者 F 使用 {变量名} 的形式来使用变量名的值 year = 2020 event = 'Referendum' value = f'Results of ...

  4. [转载] python格式化字符串漏洞_从两道CTF实例看python格式化字符串漏洞

    参考链接: Python str.format()中的漏洞 >>> name = 'Hu3sky' >>> s = Template('My name is $na ...

  5. c++字符串输入_【pwn】什么是格式化字符串漏洞?

    0x00 前言 格式化字符串漏洞是在CWE[1](Common Weakness Enumeration,通用缺陷枚举)例表中的编号为CWE-134,由于在审计过程中很容易发现该漏洞,所以此类漏洞很少 ...

  6. 在格式化字符串的边缘试探

    格式化字符串 format string基本介绍 此漏洞由printf类函数在使用时直接使用用户可控字符串作为格式化字符串使用所导致.如printf(s),在运行时,用户可以通过给予s特殊的值造成程序 ...

  7. 跟着CTF-Wiki学pwn|格式化字符串(1)

    文章目录 格式化字符串漏洞原理介绍 格式化字符串函数介绍 格式化字符串函数 格式化字符串 参数 格式化字符串漏洞原理 格式化字符串漏洞利用 程序崩溃 泄露内存 泄露栈内存 获取栈变量数值 获取栈变量对 ...

  8. C#格式化字符串净化代码的方法

    C#格式化字符串净化代码的方法,在C#编程中,字符串类型是最容易处理出错的地方,其代价往往也很昂贵,在.NET Framework中,字符串是一个不可变的类型, 当一个字符串被修改后,总是创建一个新的 ...

  9. python3格式化输出

    %s格式话字符串.%d,%f name = 'tom'age = 15weight = 72.3stu_id = 1print('我是%s,我今年%d岁了,我的体重是%.2f公斤,我的学号是%06d' ...

最新文章

  1. C++ 笔记(32)— 预处理、文件包含include、宏替换define、条件包含ifndef、define
  2. ad 卡尔曼_卡尔曼滤波剪影__Kalman Filtering · Make Intuitive
  3. Spring Cloud应用开发(三:客户端的负载均衡)
  4. linux iostat 查看磁盘io利用率
  5. mysql安装教程 没配置_MySQL安装和配置详细教程
  6. bat自动输入用户名和密码_「小白到大牛之路6」交换机后台管理之重复输入用户名和密码...
  7. 蓝桥杯 左baby右兄弟
  8. Altium Designer之PCB
  9. Csico CCNA学习笔记1_cdp telnet
  10. 数据结构 关键路径的个人理解
  11. 啦啦外卖41.8[四端全开源版本]
  12. 深雁论坛GhostXP专业装机版 V3.0
  13. java 物联网项目_物联网工程综合实践-JAVA WEB开发.ppt
  14. 本地化软件UI部分不显示的一种可能
  15. 【基础入门题048】骰子游戏(一)
  16. openwrt定时任务 2021-10-08
  17. Problem E 寻找最大元素和第二大元素
  18. 退出计算机用户的快捷方式,如何注销计算机或从Windows 10注销
  19. python元组切片_Python中如何对元组进行切片
  20. Python——describe函数值输出含义/分位值的计算和含义

热门文章

  1. 【NOIP2000】【Luogu1019】单词接龙
  2. JSP→JSTL标准标签库简介与环境搭建、JSTL助手EL表达式EL隐式对象、标签→out、set、if、多选择配合、foreach、redirect、格式化、JSTL函数标签、自定义标签、标签类架构
  3. blob 按换行 分裂_Blob对象介绍
  4. 最长回文子串manacher算法模板
  5. java中native的详解
  6. 试题2 入门训练 圆的面积
  7. HDU 5701:中位数计数
  8. PHP基础学习课程强烈推荐
  9. 在二维数组中寻找最小鞍点1181(该行最大值,该列最小值)(2种思路)
  10. [转] 面向对象编程 - 获取对象信息