格式化字符串字面值
在字符串前面使用f进行标记,标记后可以使用{}来引用外部的变量
a = "张三"
b = "法外狂徒"
c = f"我是{a},我是一名{b}"
print(c)
结果为:
我是张三,我是一名法外狂徒
让我们看看更高级的
yes_votes = 42_572_654
total_votes = 85_705_149
percentage = yes_votes / total_votes
'{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
print('{:-9} YES votes {:2.2%}'.format(yes_votes, percentage))
结果为:
42572654 YES votes 49.67%
这里,{:-9}
用于格式化yes_votes
,确保它至少有9个字符宽(不足部分用空格填充,并左对齐),而{:2.2%}
用于格式化percentage
,保留两位小数,并显示为百分比形式。
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
结果为:
spam and eggs
eggs and spam
可以通过括号中的位置来替换值
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
结果为:
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
可以通过**来直接使用字典中的值
读写文件
open(filename, mode, encoding=None),filename为文件名,mode为读写方式 ,encoding为字符编码
f = open('workfile', 'w', encoding="utf-8")
mode描述文件使用方式包含:“r”代表只读,“w”代表写入,但是会覆盖之前的文件,“a”代表追加数据,任何写入的数据都会添加至文章末尾,“r+”代表文字的读写,Mode默认值为r
在处理文件的时候最好使用"with"关键字可以保证文件可以稳定关闭
with open('workfile', encoding="utf-8") as f:
read_data = f.read()
# We can check that the file has been automatically closed.
f.closed
读
读取文件中单行的数据,当到文件末尾的时候会返回空字符串
#假设f文件已经创建出来了
f.readline()
读取多行可以使用遍历的方式
for line in f:
print(line, end='')
如果需要以列表的形式读取所有的行可以使用list(f)或者是f.readlines()
写
write可以进行写入
f.write('This is a test\n')
写入其他类型数据之前需要先将数据转化为字符串
value = ('the answer', 42)
s = str(value) # convert the tuple to string
f.write(s)
在进行文件操作的时候需要对文件进行转码
import json
x = [1, 'simple', 'list']
json.dumps(x)
#可以将文本数据转化为json格式
x = json.load(f)
#可以将Json格式变为文本文件格式