天天看點

關于python中格式化方法format()函數的詳解

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()