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

栏目: Python · 发布时间: 6年前

内容简介:在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
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computers and Intractability

Computers and Intractability

M R Garey、D S Johnson / W. H. Freeman / 1979-4-26 / GBP 53.99

This book's introduction features a humorous story of a man with a line of people behind him, who explains to his boss, "I can't find an efficient algorithm, but neither can all these famous people." ......一起来看看 《Computers and Intractability》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

随机密码生成器
随机密码生成器

多种字符组合密码