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

[编程基础] Python格式化字符串常量f-string总结的更多相关文章

  1. Python格式化字符串~转

    Python格式化字符串 在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作 ...

  2. Python格式化字符串知多少

    字符串格式化相当于字符串模板.也就是说,如果一个字符串有一部分是固定的,而另一部分是动态变化的,那么就可以将固定的部分做成模板,然后那些动态变化的部分使用字符串格式化操作符(%) 替换.如一句问候语: ...

  3. Python格式化字符串和转义字符

    地址:http://blog.chinaunix.net/uid-20794157-id-3038417.html Python格式化字符串的替代符以及含义     符   号     说     明 ...

  4. python基础之格式化字符串

    一.格式化字符功能介绍 应用场景:一般在print的时候提供占位符;python中提供两种格式化字符串方式:第一种是古老的利用百分号的方式,第二种是增强的格式化字符串.format 函数. 二.古老的 ...

  5. Python格式化字符串(f,F,format,%)

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

  6. 【转】Python格式化字符串str.format()

    原文地址:http://blog.xiayf.cn/2013/01/26/python-string-format/ 每次使用Python的格式字符串(string formatter),2.7及以上 ...

  7. Python格式化字符串

    在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作符,非常类似C语言里的pr ...

  8. Python - 格式化字符串的用法

    0. 摘要 Python支持多种格式化字符串的方法,包括%-fromatting.str.format().f-strings三种,f-strings是Python3.6以后出现的一种新方法,相比其他 ...

  9. Python格式化字符串(格式化输出)

    熟悉C语言 printf() 函数的读者能够轻而易举学会 Python print() 函数,它们是非常类似的. print() 函数使用以%开头的转换说明符对各种类型的数据进行格式化输出,具体请看下 ...

随机推荐

  1. HQL中出现XXX is not mapped的错误

    我的代码如下 @Test public void testCollection(){ String hql = "from Order where orderItems is not emp ...

  2. Linux实战笔记_ 如何远程访问Kali?

    注:基于2018年安装的kali版本. 启动ssh服务 /etc/init.d/ssh start 或 service ssh start #启动ssh服务 /etc/init.d/ssh statu ...

  3. MyBatisPlus分页插件在SpringBoot中的使用

    文章目录 1.目录结构 2.新增配置 3.编写测试类 4.测试结果 5.数据库中的表 文件的创建: https://blog.csdn.net/weixin_43304253/article/deta ...

  4. break ,continue,retrun的区别

    break ,continue,retrun的区别 1:break 在循环体内结束整个循环过程 for (var i = 1; i <= 5; i++) { if(i == 3){ break; ...

  5. app自动化测试环境安装

    一.环境依赖 app自动化测试环境如下: appium服务 第三方库appium-python-client 手机或模拟器 java环境jdk1.8 android环境 二.appium服务安装 1. ...

  6. CentOS7虚拟机配置git仓库(配置虚拟机,网络,git仓库,windows端git访问)

    想要达成的目的:从windows使用git访问CentOS7服务器上搭建的git仓库 用到的软件: (1)VMware-workstation-full-15.5.0-14665864.exe (2) ...

  7. 二、docker安装

    一.docker安装 Docker 是管理容器的工具, Docker 不等于 容器. 1.1.docker yum源设置 #step 1 download docker-ce.repo file [r ...

  8. 一、Go语言开篇介绍

    Go语言开篇介绍 Go语言 是Google公司 在2007开发一种静态强类型.编译型语言,并在 2009 年正式对外发布. Go语言以其近C的执行性能和近解析型语言的开发效率,以及近乎于完美的编译速度 ...

  9. 三、Python语法介绍

    三.Python语言介绍 3.1.了解Python语言 Python 是1989 年荷兰人 Guido van Rossum (简称 Guido)在圣诞节期间为了打发时间,发明的一门面向对象的解释性编 ...

  10. 【YOLOv5】手把手教你使用LabVIEW ONNX Runtime部署 TensorRT加速,实现YOLOv5实时物体识别(含源码)

    前言 上一篇博客给大家介绍了LabVIEW开放神经网络交互工具包[ONNX],今天我们就一起来看一下如何使用LabVIEW开放神经网络交互工具包实现TensorRT加速YOLOv5. 以下是YOLOv ...