python格式化函數foramt

來源:互聯網
上載者:User

標籤:from   name   form   www.   def   關鍵字   額的   dict   blog   

#通過位置
print ‘{0},{1}‘.format(‘chuhao‘,20)

print ‘{},{}‘.format(‘chuhao‘,20)

print ‘{1},{0},{1}‘.format(‘chuhao‘,20)

#通過關鍵字參數
print ‘{name},{age}‘.format(age=18,name=‘chuhao‘)

class Person:
def __init__(self,name,age):
self.name = name
self.age = age

def __str__(self):
return ‘This guy is {self.name},is {self.age} old‘.format(self=self)

print str(Person(‘chuhao‘,18))

#通過映射 list
a_list = [‘chuhao‘,20,‘china‘]
print ‘my name is {0[0]},from {0[2]},age is {0[1]}‘.format(a_list)
#my name is chuhao,from china,age is 20

#通過映射 dict
b_dict = {‘name‘:‘chuhao‘,‘age‘:20,‘province‘:‘shanxi‘}
print ‘my name is {name}, age is {age},from {province}‘.format(**b_dict)
#my name is chuhao, age is 20,from shanxi

#填充與對齊
print ‘{:>8}‘.format(‘189‘)
# 189
print ‘{:0>8}‘.format(‘189‘)
#00000189
print ‘{:a>8}‘.format(‘189‘)
#aaaaa189

#精度與類型f
#保留兩位小數
print ‘{:.2f}‘.format(321.33345)
#321.33

#用來做金額的千位分隔字元
print ‘{:,}‘.format(1234567890)
#1,234,567,890

#其他類型 主要就是進位了,b、d、o、x分別是二進位、十進位、八進位、十六進位。

print ‘{:b}‘.format(18) #二進位 10010
print ‘{:d}‘.format(18) #十進位 18
print ‘{:o}‘.format(18) #八進位 22
print ‘{:x}‘.format(18) #十六進位12

 

本文章轉自 https://www.cnblogs.com/gide/p/6955895.html

python格式化函數foramt

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.