Python格式化字符串f-string概览(小结)-创新互联
简介
f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便。f-string在形式上是以 f
或 F
修饰符引领的字符串(f'xxx'
或 F'xxx'
),以大括号 {}
标明被替换的字段;f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式:
While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
(与具有恒定值的其它字符串常量不同,格式化字符串实际上是运行时运算求值的表达式。)
—— Python Documentation
f-string在功能方面不逊于传统的%-formatting语句和str.format()
函数,同时性能又优于二者,且使用起来也更加简洁明了,因此对于Python3.6及以后的版本,推荐使用f-string进行字符串格式化。
用法
此部分内容主要参考以下资料:
Python Documentation – Formatted String Literals
Python Documentation – Format String Syntax
PEP 498 – Literal String Interpolation
Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
python3 f-string格式化字符串的高级用法
Python 3: An Intro to f-strings
简单使用
f-string用大括号 {}
表示被替换字段,其中直接填入替换内容:
>>> name = 'Eric' >>> f'Hello, my name is {name}' 'Hello, my name is Eric' >>> number = 7 >>> f'My lucky number is {number}' 'My lucky number is 7' >>> price = 19.99 >>> f'The price of this book is {price}' 'The price of this book is 19.99'
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享标题:Python格式化字符串f-string概览(小结)-创新互联
文章源于:http://ybzwz.com/article/djiggg.html