所有编程语言都需要支持格式化字符串功能。在 Python 中主要有以下六种方法帮助开发人员格式化字符串:

  • 连接字符串法
  • join 函数法
  • 模数运算符法
  • 含有序参数的 format 函数法
  • 含命名参数的 format 函数法
  • f-Strings 法

以上方法的使用示例如下所示。

name = 'Mark'
bus_no = 5

# 方法一:使用连接字符串
print(name + ' takes the No. ' + str(bus_no) + ' bus to work.')

# 方法二:使用 join 函数 
print(''.join([name, ' takes the No. ', str(bus_no), ' bus to work.']))

# 方法三:使用模数运算符 
print('%s takes the No. %d bus to work.' % (name, bus_no))

# 方法四:使用含有序参数的 format 函数 
print('{} takes the NO. {} bus to work.'.format(name, bus_no))

# 方法五:使用含命名参数的 format 函数 
print('{n} takes the No. {bn} bus to work.'.format(bn=bus_no, n=name))

# 方法6:使用 f-Strings (Python版本 3.6+) 
print(f'{name} takes the No. {bus_no} bus to work.')

以上方法的输出结果都是一样的:

Mark takes the No. 5 bus to work.

官方公众号

💯本站文章同步发表在官方公众号 ReadingHere,关注公众号您将在第一时间了解本站最新文章和资讯。

❤️欢迎您关注本站官方公众号 ReadingHere


版权声明

本文由ReadingHere原创,未经ReadingHere授权不得转载、摘编。已经授权使用的,应在授权范围内使用,并注明来源: www.readinghere.com。违反上述声明者,ReadingHere将追究其相关法律责任。


交流合作

如需交流咨询或商务合作请扫描下图微信二维码联系。