首页 > 编程语言 >[编程基础] Python格式化字符串常量f-string总结

[编程基础] Python格式化字符串常量f-string总结

时间:2022-12-17 20:03:11浏览次数:84  
标签:格式化 string Python 字符串 print name


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是变量名。

文章目录

  • ​​Python格式化字符串常量f-string总结​​
  • ​​1 语法​​
  • ​​1.1 Python字符串格式​​
  • ​​1.2 Python f-string中使用表达式​​
  • ​​1.3 Python f-string中使用字典​​
  • ​​1.4 Python多行f-string​​
  • ​​1.5 Python f-string对象​​
  • ​​1.6 Python f-string中转义字符​​
  • ​​1.7 Python f-string中格式化 datetime​​
  • ​​1.8 Python f-string中格式化 floats​​
  • ​​1.9 Python f-string中字符宽度​​
  • ​​1.10 Python f-string对齐字符串​​
  • ​​1.11 Python f-string中进制表示​​
  • ​​2 参考​​

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​


标签:格式化,string,Python,字符串,print,name
From: https://blog.51cto.com/luohenyueji/5950116

相关文章

  • Python+QT美颜工具源码
    OverridetheentrypointofanimageIntroducedinGitLabandGitLabRunner9.4.Readmoreaboutthe extendedconfigurationoptions.Beforeexplainingtheav......
  • 【Python】爬虫笔记-ConnectionResetError(10054)
    0x01在对网站图片进行批量爬取的过程中遇到了一个典型问题:requests.exceptions.ConnectionError:('Connectionaborted.',ConnectionResetError(10054,'Anexisting......
  • Python写个“点球大战”小游戏
    大家好,欢迎来到Crossin的编程教室!看过我Python入门教程的朋友应该会看到其中有提到一个点球小游戏的作业。在世界杯决赛即将到来之际,我们再来回顾一下这个小游戏。......
  • (数据科学学习手札147)Python GIS利器shapely全新2.0版本一览
    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes1简介大家好我是费老师,我写过很多篇介绍geopandas相关技术的文章,而geop......
  • python给文章中手机号打马赛克效果
    python中re模块练习:#coding:utf-8importrecontent="""白日依1999988****山尽,黄河入454654213213213海流。欲穷12456123千里目,更上156475***41一层楼。"""patter......
  • python之路51 聚合查询 分组查询
    图书管理系统1.表设计先考虑普通字段再考虑外键字段数据库迁移、测试数据录入2.首页展示3.书籍展示4.书籍添加5.书籍编辑后端如何获取用户想要编辑的......
  • Python 面向对象
    目录​​python继承​​​​面向对象技术简介​​​​创建类​​​​self代表类的实例,而非类​​​​创建实例对象​​​​访问属性​​​​Python内置类属性​​​​python......
  • Python中open()文件操作/OS目录操作
    File对象测试数据的读写与操作#defopen(file,mode='r',buffering=None,encoding=None,errors=None,newline=None,closefd=True):#knownspecialcaseofo......
  • f-strings: Python字符串处理的瑞士军刀
    从3.6开始,Python新增了一个格式化字符串的方法,称之为f-string。其用法就是在python原始字符串的基础上增加f/F前缀,以大括号{}标明被替换的字段。f-string在本质......
  • redis常用命令之string&list
    redis常用操做stringkey操作string<key:value>setnamejohngetnamelistsetnx<keyvalue>setnxgendermale(分布式锁)getgendersetnxgoods_1111delgoods_1ge......