這篇文章主要介紹怎么實現(xiàn)Python中字符串格式化輸出,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
Python字符串格式化輸出的四種方法:tuple形式法、字典形式、forma函數(shù)法、 StringIO模塊。下面是具體使用方法。
1、tuple形式法(方便)
print 'hello %s and %s' % ('df', 'another df')
2、字典形式(好用)
print 'hello %(first)s and %(second)s' % {'first': 'df', 'second': 'another df'}
3、forma函數(shù)法(先進(jìn))
print('姓名是 {},年齡是 {}'.format('Tom',20)) 輸出: 姓名是:Tom,年齡是:20
4、 StringIO模塊(多個數(shù)據(jù))
>>> buf = StringIO.StringIO() >>> sprintf(buf, "A = %d, B = %s\n", 3, "foo") >>> sprintf(buf, "C = %d\n", 5) >>> print(buf.getvalue()) A = 3, B = foo C = 5
以上是“怎么實現(xiàn)Python中字符串格式化輸出”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!