python格式化输出format

python格式化输出

将数据输出到文件中时:格式简单,数据类型单一的数据输出用numpy.savetxt方便快捷。格式复杂数据类型多样的数据(尤其是结构化数组)使用python自带的format功能更全面。

打印数组到屏幕

# 下面的效果相同
print('{} {:n} {}/n'.format("This is the",1,"example."))
print('{0} {1:2n} {2:s}/n'.format("This is the",1,"example."))

输出numpy数组到txt文本

import numpy as np
a = np.random.rand((10,3))
f = open("out.txt",'w')
for i in range(a.shape[0]):
  f.write('{0[0]} {0[1]} {0[2]}'.format(a[i,:])) #{}内部的数组代表所匹配的format后面括号内变量
  f.write('{0[0]:<5.3f} {0[1]:3n}\n'.format(a[i,:]) #:后面代表输出格式<代表左对齐,\n代表换行
  # {}内部的数字代表匹配变量的索引
  # :后面的格式有 整数n/d,浮点数f/F,科学计数法e/E,字符串s
f.close()

输出numpy结构化数组到txt文本

import numpy as np
a = np.random.rand((10,3))
b = np.rec.array(a.tolist(),dtype={'names':('id','argv','note'), 'formats':('int','float','U5')})
f = open("out.txt",'w')
for i in range(b.shape[0]):
  f.write('{0:<2n} {1:5.2f} {2}\n'.format(np.int(b[i,0].astype('float')),b[i,1].astype('float'),b[i,2]) 
f.close()

摘自官方文档https://docs.python.org/zh-cn/3/library/string.html?highlight=format#string.Formatter.format

posted @ 2022-03-24 21:04  Philbert  阅读(670)  评论(0编辑  收藏  举报