首页 > 其他 > 详细

str.format格式化用法(通过{}来替代%)

时间:2015-11-03 11:56:38      阅读:303      评论:0      收藏:0      [点我收藏+]
# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#str.format格式化用法(通过{}来替代%)
‘‘‘
>>> help(format)
Help on built-in function format in module __builtin__:

format(...)
    format(value[, format_spec]) -> string
    
    Returns value.__format__(format_spec)
    format_spec defaults to ""
‘‘‘



#1、通过位置:
#字符串的format函数可以接受不限个参数,位置可以不按顺序。
print name:{0},age:{1}.format(xiaodeng,28)#name:xiaodeng,age:28
print {},{}.format(xiaodeng,28)#xiaodeng,28

#print ‘{},{},{}‘.format(‘xiaodeng‘,28)
‘‘‘
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\新浪API\test.py", line 20, in <module>
    print ‘{},{},{}‘.format(‘xiaodeng‘,28)
IndexError: tuple index out of range
‘‘‘
#修改之:
print {1},{1},{0}.format(xiaodeng,28)#28,28,xiaodeng



#2、通过关键字参数:
print {name},{age}.format(age=20,name=xiaodeng)#xiaodeng,20



#3、通过对象属性:
class Person():
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        return my name is {self.name},age is {self.age} years old.format(self=self)

print Person(xiaodeng,28)#my name is xiaodeng,age is 28 old




#4、通过下标
list=[xiaodeng,28]
print {0[0]},{0[1]}.format(list)#xiaodeng,28;这里的0是默认的???



#5、填充与对齐
print {:>8}.format(125)#>右对齐,后面带宽度,<表示左对齐,^表示居中对齐。
print {:a>8}.format(125)#默认空格填充,这里为a字母填充
‘‘‘
>>>
     125
aaaaa125
>>> 
‘‘‘


#6、精度和类型f
print {:.2f}.format(321.123)#321.12;其中.2表示长度为2的精度,f表示float类型



#7、其他类型:
#要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。
print {:b}.format(17)#10001
print {:d}.format(17)#17
print  {:o}.format(17)#21
print  {:x}.format(17)#11
#用,号还能用来做金额的千位分隔符。
print {:,}.format(1234567890)#1,234,567,890


#8、指定宽度
print My name is {0:118}.format(xiaodeng)#My name is xiaodeng

 

str.format格式化用法(通过{}来替代%)

原文:http://www.cnblogs.com/dengyg200891/p/4932452.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!