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

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

posted @ 2020-06-17 20:46  落痕的寒假  阅读(61)  评论(0编辑  收藏  举报