RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Python格式化字符串f-string概览(小结)-创新互联

简介

建网站原本是网站策划师、网络程序员、网页设计师等,应用各种网络程序开发技术和网页设计技术配合操作的协同工作。成都创新互联专业提供成都网站建设、网站设计,网页设计,网站制作(企业站、成都响应式网站建设公司、电商门户网站)等服务,从网站深度策划、搜索引擎友好度优化到用户体验的提升,我们力求做到极致!

f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便。f-string在形式上是以 fF 修饰符引领的字符串(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://scyingshan.cn/article/djiggg.html