所有编程语言都需要支持格式化字符串功能。在 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.