内容简介:在Python3中,字符串格式化操作通过format()方法或者f'string'实现。而相比于老版的字符串格式化方式,format()方法拥有更多的功能,操作起来更加方便,可读性也更强。该函数将字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号不指定格式化位置,按照默认顺序格式化示例结果:
在 Python 3中,字符串格式化操作通过format()方法或者f'string'实现。而相比于老版的字符串格式化方式,format()方法拥有更多的功能,操作起来更加方便,可读性也更强。该函数将字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号 {}
作为特殊字符代替 %
。
位置设定
默认位置
不指定格式化位置,按照默认顺序格式化
S = 'I {} {}, and I\'am learning'.format('like', 'Python')
print(S)
复制代码
示例结果:
I like Python, and I'am learning 复制代码
设置位置
设置数字顺序指定格式化的位置
S = 'I {0} {1}, and I\'am learning'.format('like', 'Python')
print(S)
# 打乱顺序
S = 'I {1} {0} {1}, and I\'am learning'.format('like', 'Python')
print(S)
复制代码
示例结果:
I like Python, and I'am learning I Python like Python, and I'am learning 复制代码
设置关键字
设置关键字指定格式化的内容
S = 'I {l} {p}, and I\'am learning'.format(p='Python', l='like')
print(S)
S = 'I {p} {l}, and I\'am learning'.format(p='Python', l='like')
print(S)
复制代码
示例结果:
I like Python, and I'am learning I Python like, and I'am learning 复制代码
参数传递
我们可以传入各种类型参数格式化字符串,即不限于字符串变量或数字等。
元组传参
利用元组传参,传参形式 *tuple
# 定义一个元组
T = 'like', 'Python'
# 不指定顺序
S = 'I {} {}, and I\'am learning'.format(*T)
print(S)
# 指定顺序
S = 'I {0} {1}, and I\'am learning'.format(*T)
print(S)
复制代码
示例结果:
I like Python, and I'am learning I like Python, and I'am learning 复制代码
字典传参
# 定义一个字典
D = {'l':'like', 'p':'Python'}
# 指定键确定顺序
S = 'I {l} {p}, and I\'am learning'.format(**D)
print(S)
复制代码
示例结果:
I like Python, and I'am learning 复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Ajax设计模式
Michael Mahemoff / 杨仁和 / 电子工业出版社 / 2007-5 / 78.00元
★本书荣获LinuxWorld Linux Journal2006年Editors' Choice awards。 ★绝好的一本ajax 高级读物,建议 每个web 程序员都需要买一本,了解什么是真正的好的web设计--网友 [精彩试读一] [精彩试读二] 本书是一本关于复杂Ajax应用的整体架构设计......一起来看看 《Ajax设计模式》 这本书的介绍吧!