python格式化字符串(2):f-string简单介绍

作者:IT小样
之前已经介绍过format()函数格式化字符串,为什么还要介绍f-string呢,因为这个性能更优,而且使用起来更便捷,Python3.6以后可使用该方法格式化字符串。

简介

1.1 简单示例,直接引用

{}中是代表替换内容,可直接填入替换内容,见示例:

name = "lily"
area = "China"
f'hello,{name},welcome to {area}!'

输出:hello,lily,welcome to China!

1.2 表达式和函数

可以在{}中直接引用表达式或者函数,见示例:

name = lily
f'the division is {8/4}'
f'hello,{name.Upper()},welcome to China!'

两个分别输出:
the division is 2
hello,LILY,welcome to China!

如果想了解format()函数如何格式化字符串,可以点击链接查看:
format()格式化字符串

发布了39 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_31315135/article/details/89092678