品易云推流 关闭
文章详情页
文章 > Python基础教程 > 如何实现Python中字符串格式化输出?

如何实现Python中字符串格式化输出?

头像

宋雪维

2020-12-11 18:21:032020浏览 · 0收藏 · 0评论

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

以上就是字符串格式化输出的四种方法,大家根据不同情况可以选择合适的方法,希望能帮到你哦~

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图