f
或 F
。在此字符串中,你可以在 {
和 }
字符之间写可以引用的变量或字面值的 Python 表达式。>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'
{
和 }
来标记变量将被替换的位置,并且可以提供详细的格式化指令,但你还需要提供要格式化的信息>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
‘:‘
后传递一个整数可以让该字段成为最小字符宽度。这在使列对齐时很有用。:>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
‘!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'.
花括号和其中的字符(称为格式字段)将替换为传递给 str.format()
方法的对象。花括号中的数字可用来表示传递给 str.format() 方法的对象的位置。
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
字符串对象的 str.just() 方法通过在左侧填充空格来对给定宽度的字段中的字符串进行右对齐。类似的方法还有 str.ljust() 和 str.center()
open()
返回一个 file object,最常用的有两个参数: open(filename, mode)
。
>>> f = open('workfile', 'w')
第一个参数是包含文件名的字符串。第二个参数是另一个字符串,其中包含一些描述文件使用方式的字符。mode 可以是 ‘r‘
,表示文件只能读取,‘w‘
表示只能写入(已存在的同名文件会被删除),还有 ‘a‘
表示打开文件以追加内容;任何写入的数据会自动添加到文件的末尾。‘r+‘
表示打开文件进行读写。mode 参数是可选的;省略时默认为 ‘r‘
。
在处理文件对象时,最好使用 with 关键字。 优点是当子句体结束后文件会正确关闭,即使在某个时刻引发了异常。 而且使用 with
相比等效的 try
-finally
代码块要简短得多:
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
True
原文:https://www.cnblogs.com/jestland/p/11585941.html