当前位置 : 主页 > 编程语言 > python >

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

来源:互联网 收集:自由互联 发布时间:2022-06-14
文章目录 ​​preface​​ ​​[overview]​​ ​​常用字符串操作​​ ​​format()方法 字符串格式化操作​​ ​​f-string 字符串​​ ​​f-string​​ ​​f-string examples:​​ ​​format sp


文章目录

  • ​​preface​​
  • ​​[overview]​​
  • ​​常用字符串操作​​
  • ​​format()方法 字符串格式化操作​​
  • ​​f-string 字符串​​
  • ​​f-string​​
  • ​​f-string examples:​​
  • ​​format specifiers​​
  • ​​Raw f-string​​


preface

  • 到目前位置,我认为python的字符串插值语法在诸多现代编程语言中是最为方便的,允许你在字符串中直接使用​​{}​​​来指明一个表达式,而统一地将指示该字符串是一个插值字符串的​​f​​提到字符串的前面
  • python 提供了两种现代化的字符串格式化方法:format()和f-string
  • 前者的风格更像正则表达式分组中的操作
  • 后者更加简单,内联替换变量名为字符串,阅读起来更加方便

[overview]

​​overview​​​​https://docs.python.org/zh-cn/3/library/string.html#format-string-syntax​​

​​目录​​

  • ​string​​ — 常见的字符串操作
  • ​​字符串常量​​
  • ​​自定义字符串格式化​​

常用字符串操作

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

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

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

f-string 字符串

  • 格式字符串语法
  • ​​格式规格迷你语言​​
  • ​​格式示例​​
  • ​​模板字符串​​
  • ​​辅助函数​​

f-string

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

  • a f-string looks like:
    ​​​f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '​

  • 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

​​https://www.python.org/dev/peps/pep-0498/#id30​​​python_字符串操作及其格式化/模板字符串(f-string:interpolation/str.format())(by official document)_python

Raw f-string

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


【本文来自:日本服务器 http://www.558idc.com/jap.html 复制请保留原URL】
网友评论