Python字符串格式化输出是我们在操作字符串时遇到的形式,本文主要介绍Python字符串格式化输出的四种方法:tuple形式法、字典形式、forma函数法、 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函数法(先进)
print('姓名是 {},年龄是 {}'.format('Tom',20)) 输出: 姓名是:Tom,年龄是:20
4、 StringIO模块(多个数据)
>>> 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
以上就是字符串格式化输出的四种方法,大家根据不同情况可以选择合适的方法,希望能帮到你哦~
Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务