【Python】 字符串格式

今天的目标

输出字符串的场景有很多,所以来了解一下生成字符串的各种方式。

字符串生成

字符串连接

到目前为止,可能已经在代码中多次看到字符串连接,但再次看一下。

python 复制代码
'ap' 'ple' 
'ap' + 'ple'
python 复制代码
'apple'
'apple'

如上所示,可以使用或不使用 + 运算符来连接字符串。

format方法

通过使用格式方法,只需更改格式方法的参数即可更改输出结果。

python 复制代码
'My favorit fruits are {0} and {1}'.format('apple', 'peach')
python 复制代码
'My favorit fruits are apple and peach'

如上所示,如果用 {} 包围索引并将其嵌入到字符串中,则该字符串将与 format 方法的参数索引一起输出。

因此,如果更改如下指定的索引,将得到相应的输出结果。

python 复制代码
'My favorit fruits are {1} and {0}'.format('apple', 'peach')
python 复制代码
'My favorit fruits are peach and apple'

format 方法还支持关键字参数和字典。

python 复制代码
#关键字参数
'My favorit fruits are {fruit1} and {fruit2}'.format(fruit1='apple', fruit2='peach')
python 复制代码
'My favorit fruits are apple and peach'
python 复制代码
字典
basket = {'fruit1':'apple', 'fruit2':'peach'}
'My favorit fruits are {0[fruit1]} and {0[fruit2]}'.format(basket)
python 复制代码
'My favorit fruits are apple and peach'

使用字典时,可以将其解包以简化指定方法。

python 复制代码
字典
basket = {'fruit1':'apple', 'fruit2':'peach'}
'My favorit fruits are {fruit1} and {fruit2}'.format(**basket)
python 复制代码
'My favorit fruits are apple and peach'

它还可用于格式化数字。 对于数值,可以指定要显示的小数位数,如下所示。

python 复制代码
score = 98.75
'My score is {0:.1f}'.format(score)
python 复制代码
'My score is 98.8'

与之前一样,{0:.1f} 中的 0 指定参数的索引。 .1f表示显示多少位小数,f代表浮点float。

在本规范中,您可以看到该数字四舍五入到小数点后第二位。

后记

f-strings表示法

文章发表后,评论里告诉我这是一个非常强大的符号,所以我想介绍给大家!

这是一种称为 f-strings或格式化字符串文字的表示法。

上面使用了format方法来替换占位符,但是使用 f-string 表示法允许直接嵌入变量。

该表示法是通过在要定义的字符串的开头添加 f 或 F 来定义的。

*由于Python 3.6或更高版本支持,请注意执行环境。

python 复制代码
str1 = 'apple'
str2 = 'peach'

f'My favorit fruits are {str1} and {str2}'
python 复制代码
'My favorit fruits are apple and peach'
python 复制代码
score = 98.75

f'My score is {score:.1f}'
python 复制代码
'My score is 98.8'
相关推荐
tao35566719 分钟前
【Python刷力扣hot100】42. Trapping Rain Water
开发语言·python·leetcode
一只安22 分钟前
从零开发AI(不依赖任何模型)
人工智能·python
2501_9387820929 分钟前
实战 Python NLP:处理 PDF 文档批量提取文本并进行主题建模
python·自然语言处理·pdf
成长痕迹38 分钟前
【Python与Matlab数据分析对比】
python·matlab·数据分析
11年老程序猿在线搬砖41 分钟前
如何搭建自己的量化交易平台
大数据·人工智能·python·自动交易·量化交易系统
消失的旧时光-19431 小时前
Kotlin 协程最佳实践:用 CoroutineScope + SupervisorJob 替代 Timer,实现优雅周期任务调度
android·开发语言·kotlin
错把套路当深情1 小时前
Kotlin保留小数位的三种方法
开发语言·python·kotlin
错把套路当深情1 小时前
Kotlin基础类型扩展函数使用指南
python·微信·kotlin
千里码aicood1 小时前
python+vue旅游购票管理系统设计(源码+文档+调试+基础修改+答疑)
vue.js·python·旅游
B站_计算机毕业设计之家1 小时前
python电商商品评论数据分析可视化系统 爬虫 数据采集 Flask框架 NLP情感分析 LDA主题分析 Bayes评论分类(源码) ✅
大数据·hadoop·爬虫·python·算法·数据分析·1024程序员节