1.format()的基本用法
Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法;
字符串的参数使用{NUM}进行表示,0, 表示第一个参数,1, 表示第二个参数, 以后顺次递加;
使用":", 指定代表元素需要的操作, 如":.3"小数点三位, ":8"占8个字符空间等;
2.format使用的简单例子
# -*- coding: utf-8 -*-
#====================
#File: abop.py
#Author: Wendy
#Date: 2013-12-03
#====================
#eclipse pydev, python3.3
age = 25
name = 'Caroline'
print('{0} is {1} years old. '.format(name, age)) #输出参数
print('{0} is a girl. '.format(name))
print('{0:.3} is a decimal. '.format(1/3)) #小数点后三位
print('{0:_^11} is a 11 length. '.format(name)) #使用_补齐空位
print('{first} is as {second}. '.format(first=name, second='Wendy')) #别名替换
print('My name is {0.name}'.format(open('out.txt', 'w'))) #调用方法
print('My name is {0:8}.'.format('Fred')) #指定宽度
# 输出结果
Caroline is 25 years old.
Caroline is a girl.
0.333 is a decimal.
_Caroline__ is a 11 length.
Caroline is as Wendy.
My name is out.txt
My name is Fred .
3.比较实用的format,比如把format写入文件
file1 = open("abc.txt","w")
for temp in range(10):
file1.write("{:<10} {:<8}\n".format("abc","bcd"))
#:<10,指这个元素占10个,不到10个在后面补充空格
file1.close()