Python string formatting: %-formatting, str.format(), f-strings

目录

1. 概要

2. %-formatting

3. str.format()

4. f-strings


1. 概要

        Python中有三种字符串格式化的方式:

        (1) %-formatting

        (2) str.format()

        (3) f-strings

        本文简要介绍这三种字符格式化方法的使用方式。

2. %-formatting

      %-formatting是最古老的字符串格式化方式,是从python问世以来就有的。

      %-formatting的使用方式如下所示:

myname = 'Chen Xiaoyuan'
print("Hello, I am %s." % myname)

        如果需要插入多个变量的话,需要将这些变量组合成一个tuple使用,如下所示:

myname = 'Chen Xiaoyuan'
profession = '​chip architect'
years  = 20
print("Hello, I am %s. I am a %s, with more than %s years experience" % (myname,profession,years))

        但是,这种化石级方式已经不受推荐使用了,python官方文档有如下描述:

“The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).

Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.”

3. str.format()

        str.format()是从python2.6开始导入的新的方式。

        基本使用方法如下所示:

myname = 'Chen Xiaoyuan'
profession = '​chip architect'
years  = 20
print("Hello, I am {}. I am a {}, with more than {} years experience".format(myname,profession,years))

        如上所示,相比%-formatting,字符串替代符用“{}” 替换了%s,用format()替换了% ()。如果仅仅是这样的话,当然就体现不出str.format()方式有啥子好的了。

        str.format()中可以通过它们的位置序号来引用,如下所示:

print("Hello, I am {1}, I am {0} " .format (profession, myname) )    

        可以重复引用,按任意顺序引用,如下所示:

print("\
Hello, I am {1}, I am {0} \n\
       I am {0}, I am {1} \n\
       I am {1}, I am {0} \n\
       -- The important things should be said three times "\
       .format (profession, myname) )  

        在{}中还可以进行诸如数据精度指定之类的格式化,比如说:

import math
print('pi = {0:6.5f}, {0:10.9f}'.format(math.pi))

        这后面几个例子充分体现了str.format()相比%-formatting的功能强大和灵活性 。

4. f-strings

        f-strings也称为“formatted string literals”,是从python3.6导入的。其特征是:

        (1) 格式为:f'   '

        (2) 在运行时进行评估

        (3) 基于__format__ protocol进行格式化

        简单的例子:

first_name = "Xiaoyuan"
last_name  = "Chen"
profession = "chip architect"
city       = "Shanghai"
print(f"Hello, I am {last_name} {first_name}. I am living in {city} ")
print(F"Hello, I am {last_name} {first_name}. I am living in {city} ")

        如上所示,格式上与str.format()相似,但是显得更加简洁。

        由于f-strings是在运行中进行评估的,你可以把任意有效的python表达式放在其中,比如说数学表达式,甚至函数调用或者方法调用,如下所示:

# You could do something pretty straightforward, like this:

print(f'5! = {5*4*3*2*1}')

# You could do function call or method call inside f-string:
print(f'{myname.lower()} is a chip architect and algorithm engineer')    

def factorial(k):
    if k <= 1:
        return 1
    prod = 1
    for i in range(2,k+1):
        prod *= i
    return prod

print(f'20! = {factorial(20)}')   

        f-strings不仅比str.format()要更为强大和灵活,而且运行速度也更快。

        可以参考以下网页了解更多fancier details,还有python官方文档。

ref:

Python 3's f-Strings: An Improved String Formatting Syntax (Guide)

猜你喜欢

转载自blog.csdn.net/chenxy_bwave/article/details/130448507
今日推荐