python的字符串插值语法,允许你在字符串中直接使用{}
来指明一个表达式,而统一地将指示该字符串是一个插值字符串的f
提到字符串的前面
python 提供了两种现代化的字符串格式化方法:format()和f-string
7. Input and Output — Python 3.11.1 documentation
7. 输入与输出
json
保存结构化数据printf 风格的字符串格式化
% 运算符(和求余符一样的符号)也可用于字符串格式化。
给定 'string' % values
,则 string
中的 %
实例会以零个或多个 values
元素替换。
此操作被称为字符串插值。例如:
>>> a=10
>>> "test%d"%a
'test10'
>>> "test%s"%5.6
'test5.6'
>>> "test:try wide test%10f"%5.6
'test:try wide test 5.600000'
>>>
>>> type("test%s"%5.6)
<class 'str'>
和C语言的最大不同在于,python中的'string%type' %values
表达式本身计算结果可以独立存在
import math
print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.
print("place%d" % cnt)
print('[%d,%d],mid:%d' %(l,r, mid))#按照位置对应(3个变量)
string —对比两种字符串格式化方式
内置类型str.format函数原型 — Python 文档
string — 常见的字符串操作
PEP 3101 – Advanced String Formatting | peps.python
python字符串的第二种格式化方式
比类C语言的printf()更加强大,支持的操作也更加的丰富
这种格式化方法,是编写一个格式字符串(包含格式化目标的字符串的结构信息)
structure_str
structure_str.foramt()
然后将具体的值填充到对应的位置,组织成需要的目标字符串
>>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'a, b, c'
'{}, {:^5}, {}'.format('a', 'b', 'c')
# 'a, b , c'
按位置访问参数:
比如更好的支持复用以及变量插入字符串顺序调整
>>> '{0} {1} {0}'.format('abra', 'cad') # arguments' indices can be repeated
'abra cad abra'
支持字符串对象解包
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'c, b, a'
>>> '{1}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'b, b, a'
按名称访问参数:
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
访问对象属性
下面一个python自带的复数对象为例
>>> c = 3-5j
>>> c
(3-5j)
>>> c.real
3.0
>>> c.imag
-5.0
>>> d=4+2j
>>> d
(4+2j)
>>> ('The complex number {0} is formed from the real part {0.real} '
... 'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'>>> 'The complex number:{0},{1};imag parts:({0.imag}),({1.imag}) '.format(c,d)
'The complex number:(3-5j),(4+2j);imag parts:(-5.0),(2.0) '
访问参数的项:
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'
%s
,%r
🎈>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
!r
和%r
都可以用于在字符串格式化中将一个值转换为其repr()
形式,但它们的语法有所不同。
!r
是一种新的格式化语法,它出现在使用str.format()
方法或者f-strings时。它的作用是对传入的值进行repr()
处理,以便在字符串中显示它们的原始表示形式。例如,'Hello, {!r}!'.format('world')
将产生结果'Hello, 'world'!'
,而不是'Hello, world!'
。%r
是旧的格式化语法,它出现在使用%
运算符时。它的功能与!r
相同,即对传入的值进行repr()
处理,并将其插入到格式化字符串中。例如,'Hello, %r!' % 'world'
将产生结果'Hello, 'world'!'
。!r
语法。如果使用较旧版本的Python,或者在某些情况下无法使用!r
,则可以考虑使用%r
。>>> '{:<30}'.format('left aligned')
'left aligned '
>>>
>>> '{:>30}'.format('right aligned')
' right aligned'
>>>
>>> '{:^30}'.format('centered')
' centered '
>>>
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
替代 %+f
, %-f
和 % f
以及指定正负号:
'{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
'{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
'{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
替代 %x
和 %o
以及转换基于不同进位制的值:
# format also supports binary numbers
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)# with 0x, 0o, or 0b as prefix:
"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
逗号作为千位分隔符
'{:,}'.format(1234567890)'1,234,567,890'
表示为百分数
points = 19
total = 22
'Correct answers: {:.2%}'.format(points/total)'Correct answers: 86.36%'
#双阶乘
from functools import reduce
def df_basic(n):l = range(n, 0, -2)res = reduce(lambda x, y: x * y, l)list_str = str(list(l))print("n=%-3d-->" % n, "{:-^30}".format(list_str), "product_res=%d" % res)return restest_list = [3, 4, 5, 8, 9, 16]
res = list(map(df_basic, test_list))
PS D:reposPythonLearnscripts> py double_factorial.py
n=3 --> ------------[3, 1]------------ product_res=3
n=4 --> ------------[4, 2]------------ product_res=8
n=5 --> ----------[5, 3, 1]----------- product_res=15
n=8 --> ---------[8, 6, 4, 2]--------- product_res=384
n=9 --> -------[9, 7, 5, 3, 1]-------- product_res=945
n=16 --> -[16, 14, 12, 10, 8, 6, 4, 2]- product_res=10321920
PEP 498 – Literal String Interpolation
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”.
import datetimename = 'Fred'age = 50anniversary = 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'."
specifiers
Format specifiers may also contain evaluated expressions. This allows code such as:
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result: 12.35'
str.format()
, they are merely passed in to the __format__()
method of the object being formatted.控制一个字符串格式,可以分为2部分
上述这些方式中,他们都是变量在前,而控制格式在后
只有f-string方式中,格式控制是在变量之后
s=123
print("[%10s]"%s)
print("[%10s]"%(str(s).center(10)))
print("[{:^10}]".format(s))
print(f"[{s:^10}]")
print(f"[{format(s,'^10')}]")
[ 123]
[ 123 ]
[ 123 ]
[ 123 ]
[ 123 ]
f-string可读性强,但是由于不像shell语言(比如powershell)和Kotlin
那样可以不许在字符串前插入f
,写起来手感差一些
所以实际操作中通常建议坚持一种格式控制方式,先想好控制格式,然后开始写代码
f-strings是最简洁和易读的字符串格式化方法,同时还支持更多的功能,例如表达式求值、函数调用等。但是,它只能在Python 3.6及以上的版本中使用。而%风格的字符串格式化和str.format()方法则可以在Python 2.x和Python 3.x中使用,但是语法稍微繁琐一些。
var=np.random.rand(3,4)
print(var,'@{var}')#这里用{}是为了能够利用IDE的变量不全提示而已,@也可以自由取舍和修改
[[0.11348592 0.27222936 0.08205775 0.76527058][0.02168872 0.13725135 0.26062867 0.87108257][0.17941007 0.43327873 0.32511791 0.58340419]] @{var}
对比:
var=np.random.rand(3,4)
print(f'{var=}')
var=array([[0.65701977, 0.65230895, 0.82171856, 0.40276676],[0.03756505, 0.98463162, 0.44814283, 0.93763523],[0.67204106, 0.26669688, 0.56406436, 0.95693298]])
词法分析 — Python 3文档
字符串和编码 (liaoxuefeng)
Text Sequence Type — [str
]
Built-in Types — Python 3.10.4 documentation
é
,在希伯来语编码中却代表了字母Gimel (ג)
以python为例,调用字符串(str)类型的对象的编码方法(encode),将字符串编码转换为字节对象(bytes)
>>> a="text"
>>> a.encode('utf-8')
b'text'
>>> bde('utf-8')
>>> b
b'text'
>>> type(b)
<class 'bytes'>
>>> type(a)
<class 'str'>
>>> c="测试".encode('utf-8')
>>> c
b'xe6xb5x8bxe8xafx95'
>>> len(c)
6
#可见,两个中文字符(字符串长度为2),被编码为utf-8的字节后,占了6个字节
>>> c.decode('utf-8')
'测试'
>>> type(c)
<class 'bytes'>
>>> d=c.decode('utf-8')
>>> type(d)
<class 'str'>
>>> len(d)
2
r
prefix to disable processing of escape sequences. See String and Bytes literals for more about the various forms of bytes literal, including supported escape sequences.本文发布于:2024-01-30 15:20:01,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170659920520946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |