06_格式化输入与输出
格式化输入与输出
格式化字符串字面值
在字符串前面加前缀 f或F
通过
{expression}表达式,把 Python 表达式的值添加到字符串内
first_value = 1
second_value = 2
print(f'first_value = {first_value}, second_value = {second_value}')
>>>first_value = 1, second_value = 2
格式说明符:是可选的,通过:来控制格式化值的方式
如下是将pi保留三位小数输出
from math import pi
print(pi)
print(f'pi = {pi:.3f}')
3.141592653589793
pi = 3.142
在:后传递整数,可以为该字段设置最小字符宽度,常用于列对齐
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, num in table.items(): #使用items()取出键值对
print(f'{name:10}---{num:10}')
Sjoerd --- 4127
Jack --- 4098
Dcab --- 7678
TO_STUDY
还有一些修饰符可以在格式化前转换值。 '!a' 应用 ascii() ,'!s' 应用 str(),'!r' 应用 repr():
>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.
= 说明符可被用于将一个表达式扩展为表达式文本、等号再加表达式求值结果的形式。
>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
字符串 format() 方法
通过str.format()格式化字符串
-
通过
{}控制字符的位置print('first_str = {}, second_str = {}'.format('first', 'second')) >>> first_str = first, second_str = second -
可以在
{}中传递数字,来控制str.format()中的值的位置print('first_str = {0}, second_str = {1}'.format('first', 'second')) print('first_str = {1}, second_str = {0}'.format('first', 'second')) >>> first_str = first, second_str = second first_str = second, second_str = first -
也可以通过设置关键词参数来控制值的位置
print('first_str = {first}, second = {second}'.format( first = 'first', second = 'second')) >>> first_str = first, second = second -
传递数字和关键词参数可以同时使用
print('first_str = {}, second = {second}'.format( 'first', second = 'second')) >>> first_str = first, second = second
str() & repr()
str()函数返回供人阅读的值,repr()则生成适于解释器读取的值(如果没有等效的语法,则强制执行SyntaxError)。对于没有支持供人阅读展示结果的对象,str()返回与repr()相同的值。一般情况下,数字、列表或字典等结构的值,使用这两个函数输出的表现形式是一样的。
#str() & repr()#str() & repr()
print(str('hello word'))
print(repr('hello word'))
print(str(1))
print(repr(1))
print(str('hello \n word'))
print(repr('hello \n word'))
print(repr((1, '3', ('1', 2))))
hello word
'hello word'
1
1
hello
word
'hello \n word'
(1, '3', ('1', 2)
浙公网安备 33010602011771号