导航
  • 报考
  • 备考
  • 政策

报考

备考

复习资料

政策

行业动态

让python的使用变得简便—— 字符串的 format() 方法(上)

环球青藤·2019-09-25 13:27:07浏览33 收藏16

请输入下面的图形验证码

提交验证

预约成功

我知道了
摘要 有几种方法可以显示程序的输出;数据可以以人类可读的形式打印出来,或者写入文件以供将来使用。小编将和大家讨论一些有关于输入输出可能性。

str.format() 方法的基本用法如下所示:

>>>>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))

We are the knights who say "Ni!"

花括号和其中的字符(称为格式字段)将替换为传递给 str.format() 方法的对象。花括号中的数字可用来表示传递给 str.format() 方法的对象的位置。

>>>>>> print('{0} and {1}'.format('spam', 'eggs'))

spam and eggs

>>> print('{1} and {0}'.format('spam', 'eggs'))

eggs and spam

如果在 str.format() 方法中使用关键字参数,则使用参数的名称引用它们的值。:

>>>>>> print('This {food} is {adjective}.'.format(

... food='spam', adjective='absolutely horrible'))

This spam is absolutely horrible.

位置和关键字参数可以任意组合:

>>>>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',

other='Georg'))

The story of Bill, Manfred, and Georg.

以上就是本章的内容。

资料下载
历年真题
精选课程
老师直播

注册电脑版

版权所有©环球青藤All Rights Reserved