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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值