Python格式化输出以及保存

mac2024-05-14  30

一、Python格式化输出

1、%格式化输出

1.1、输出字符串

>>> a='AAAA' >>> b='BBBB' >>> print('a=%s b=%s' %(a,b)); a=AAAA b=BBBB

1.2、 打印整数

>>> a=10 >>> b=20 >>> print('a=%d b=%d' %(a,b)); a=10 b=20

1.3、打印浮点数

>>> a=1.1234 >>> b=3.14159; >>> print('a=%d b=%d' %(a,b)); a=1 b=3 >>> print('a=%f b=%f' %(a,b)); a=1.123400 b=3.141590

1.4、打印浮点数(指定保留小数点位数)

>>> a=1.1234 >>> b=3.14159; >>> print('a=%.2f b=%.3f' %(a,b)); a=1.12 b=3.142

2、format 格式化输出

"hello {}".format("python") # 引用一个参数 传字符串 # 输出:hello python "hello {}".format(1024) # 传数字 # 输出:hello 1024 "hello {}".format([1, 2, 3, 4]) # 传列表 # 输出:hello [1, 2, 3, 4] "hello {}".format((1, 2, 3, 4)) # 传元组 # 输出:hello (1, 2, 3, 4) "hello {}".format({"name": "chenkia", "age": 18}) # 传字典 # 输出:hello {'name': 'chenkia', 'age': 18} "hello {}".format({"name", "chenkai", "name", "akai"}) # 传集合 # 输出:hello {'chenkai', 'akai', 'name'}

二、Python保存数据的方法

2.1、 open函数保存

 open函数的打开模式

参数用法rread只读。若不存在文件会报错。wwrite只写。若不存在文件会自动新建。aapend附加到文件末尾。rb, wb, ab操作二进制r+读写模式打开

 

#保存数据open函数 with open('D:/PythonWorkSpace/TestData/pinglun.txt','w',encoding='utf-8') as f:#使用with open()新建对象f for i in comments: print(i) f.write(i+'\n')#写入数据,文件保存在上面指定的目录,加\n为了换行更方便阅读

2.2 、pandas保存数据到CSV和Excel

#导入包 import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10,4))#创建随机值 df.to_excel('D:/PythonWorkSpace/TestData/PandasNumpy.xlsx') df.to_csv('D:/PythonWorkSpace/TestData/PandasNumpy.csv')

 

最新回复(0)