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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笨牛慢耕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值