栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python3之字符串格式化format函数详解(上)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python3之字符串格式化format函数详解(上)

概述

在Python3中,字符串格式化操作通过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
列表传参
# 定义一个列表
L0 = ['like', 'Python']
L1 = [' ', 'Lerning']
# `[]`前的0、1用于指定传入的列表顺序
S = 'I {0[0]} {1[1]}, and I'am learning'.format(L0, L1)
print(S)

示例结果:

I like Lerning, and I'am learning
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号