python_字符串操作及其格式化/模板字符串(f-string:interpolation/str.format())(by official document)

网友投稿 329 2022-08-30


python_字符串操作及其格式化/模板字符串(f-string:interpolation/str.format())(by official document)

文章目录

​​preface​​

​​[overview]​​​​常用字符串操作​​​​format()方法 字符串格式化操作​​​​f-string 字符串​​

​​f-string​​​​f-string examples:​​​​format specifiers​​​​Raw f-string​​

preface

到目前位置,我认为python的字符串插值语法在诸多现代编程语言中是最为方便的,允许你在字符串中直接使用​​{}​​​来指明一个表达式,而统一地将指示该字符串是一个插值字符串的​​f​​提到字符串的前面python 提供了两种现代化的字符串格式化方法:format()和f-string

前者的风格更像正则表达式分组中的操作后者更加简单,内联替换变量名为字符串,阅读起来更加方便

[overview]

​​overview​​​​— 常见的字符串操作

​​字符串常量​​​​自定义字符串格式化​​

常用字符串操作

​​string — 常见的字符串操作 ​​

format()方法 字符串格式化操作

​​内置类型str.format — Python 文档​​​​PEP 3101 – Advanced String Formatting | peps.python.org​​

f-string 字符串

格式字符串语法

​​格式规格迷你语言​​​​格式示例​​

​​模板字符串​​​​辅助函数​​

f-string

​​f-string looks like:​​​f ' { } ... '​​

Python supports multiple ways to format text strings.These include​​%-formatting​​​ [​​1]​​​,​​str.format()​​​ [​​2]​​​, and​​string.Template​​​ [​​3]​​.Each of these methods have their advantages, but in addition have disadvantages that make them cumbersome to use in practice.This PEP proposed to add a new string formatting mechanism: Literal String Interpolation. In this PEP, such strings will be referred to as “f-strings”, taken from the leading character used to denote such strings, and standing for “formatted strings”.

f-string examples:

import datetime name = 'Fred' age = 50 anniversary = datetime.date(1991, 10, 12) # example1: f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.' >>> 'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.' # example2: f'He said his name is {name!r}.' >>>"He said his name is 'Fred'."

format specifiers

Raw f-string

​​https://python.org/dev/peps/pep-0498/#id43​​


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python_表情分类问题(主要是数据读取)_尚未降维(基于python的表情识别)
下一篇:mybatis foreach遍历LIST读到数据为null的问题
相关文章

 发表评论

暂时没有评论,来抢沙发吧~