August Rush

一个还在努力成长的小火汁!

游龙当归海,海不迎我自来也。

We create our own demons.

You can reach me at augustrush0923@gmail.com
f-Strings:格式化输出
发布:2020年09月14日 | 作者:augustrush | 阅读量: 1103

这几天一直在看PEP新特性,偶然看到PEP 498的新特性。真是遇到宝藏了。真的太好用了!现在总结记录一下。

PEP 498 是python3.6开始加入标准库的格式化输出新的写法,这个格式化输出比之前的%s 或者 format 效率高并且更加简化,非常的好用,相信我,你们学完这个之后,以后再用格式化输出这就是你们唯一的选择。

# python 3.6之前字符串格式化写法
name = "August Rush"
age = 18

print("Hello! I'm %s, and I'm %s years old" % (name, age))  # 3.6之前的拼接字符串
print("Hello! I'm {}, and I'm {} years old".format(name, age))  # 3.6之前的拼接字符串

简单例子


他的结构就是F(f)+ str的形式,在字符串中想替换的位置用{}展位,与format类似,但是用在字符串后面写入替换的内容,而他可以直接识别。碉堡了。

# python 3.6 PEP 498新特性:f-Strings
print(F"Hello! I'm {name}, and I'm {age} years old")
print(f"Hello! I'm {name}, and I'm {age} years old")
"""
输出结果:
Hello! I'm August Rush, and I'm 18 years old
"""


任意表达式

他可以加任意的表达式,非常方便:

print(F"Hello! I'm {name}, and I'm {age+4} years old")  # 任意表达式
print(f"Hello! I'm {name.lower()}, and I'm {age} years old")  # 任意表达式

info_dict = {'name': 'August Rush', 'age': 18}
print(f"Hello! I'm {info_dict[name]}, and I'm {info_dict[age]} years old")  # 字典

info_list = ['august rush', 18]
print(f"Hello! I'm {info_list[0]}, and I'm {info_list[1]} years old")  # 列表

info_tuple = ('august rush', 18)
print(f"Hello! I'm {info_tuple[0]}, and I'm {info_tuple[1]} years old")  # 元组


# 可以用函数完成相应的功能,然后将返回值返回到字符串相应的位置
def sum_a_b(a, b):
    return a + b


print(f"a + b = {sum_a_b(a=1, b=2)}")  # 函数表达式
print(f"x = {(lambda x : x*2)(x=5)}")  # 匿名函数
"""
输出结果:
Hello! I'm August Rush, and I'm 22 years old
Hello! I'm august rush, and I'm 18 years old
Hello! I'm august rush, and I'm 18 years old
Hello! I'm august rush, and I'm 18 years old
a + b = 3
x = 10
"""


多行f


place = "theater"
mood = "interesting"
speaker = f"""
    Last week I went to a {place},
    I had a very good seat,
    The play was very {mood}!
"""
speaker = f'Last week I went to a {place}.\n'\
    f'I had a very good seat.\n'\
    f'The play was very {mood},\n'\
    f"but I did not enjoy it.\n"
print(speaker)

"""
输出结果:
Last week I went to a theater.
I had a very good seat.
The play was very interesting,
but I did not enjoy it.
"""

其他细节

这里有一些注意的细节,了解一下就行。

print(f"{{73}}")  # {73}
print(f"{{{73}}}")  # {73}
print(f"{{{{73}}}}")  # {{73}}
m = 21
# ! , : { } ;这些标点不能出现在{} 这里面。
# print(f'{;12}')  # 报错
# 所以使用lambda 表达式会出现一些问题。
# 解决方式:可将lambda嵌套在圆括号里面解决此问题。
x = 5
print(f'{(lambda x: x*2) (x)}')  # 10


  • 标签云

  • 支付宝扫码支持一下

  • 微信扫码支持一下



基于Nginx+Supervisord+uWSGI+Django1.11.1+Python3.6.5构建

京ICP备20007446号-1 & 豫公网安备 41100202000460号

网站地图 & RSS | Feed