Python 中字符串拼接的多种方法
作者:木头释然 时间:2023-09-25 07:02:13
python拼接字符串一般有以下几种方法:
①直接通过(+)操作符拼接
s = 'Hello'+' '+'World'+'!'
print(s)
输出结果: Hello World!
使用这种方式进行字符串连接的操作效率低下,因为python中使用 + 拼接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当拼接字符串较多时自然会影响效率。
②通过str.join()方法拼接
strlist=['Hello',' ','World','!']
print(''.join(strlist))
输出结果: Hello World!
这种方式一般常使用在将集合转化为字符串,''.join()其中''可以是空字符,也可以是任意其他字符,当是任意其他字符时,集合中字符串会被该字符隔开,例如:
strlist=['Hello',' ','World','!']
print(','.join(strlist))
输出结果: Hello, ,World,!
③通过str.format()方法拼接
s='{} {}!'.format('Hello','World')
print(s)
输出结果: Hello World!
通过这种方式拼接字符串需要注意的是字符串中{}的数量要和format方法参数数量一致,否则会报错。
④通过(%)操作符拼接
s = '%s %s!' % ('Hello', 'World')
print(s)
输出结果: Hello World!
这种方式与str.format()使用方式基本一致。
⑤通过()多行拼接
s = (
'Hello'
' '
'World'
'!'
)
print(s)
输出结果: Hello World!
python遇到未闭合的小括号,自动将多行拼接为一行。
⑥通过string模块中的Template对象拼接
from string import Template
s = Template('${s1} ${s2}!')
print(s.safe_substitute(s1='Hello',s2='World'))
输出结果: Hello World!
Template的实现方式是首先通过Template初始化一个字符串。这些字符串中包含了一个个key。通过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这种方式的好处是不需要担心参数不一致引发异常,如:
from string import Template
s = Template('${s1} ${s2} ${s3}!')
print(s.safe_substitute(s1='Hello',s2='World'))
输出结果: Hello World ${s3}!
⑦通过F-strings拼接
在python3.6.2版本中,PEP 498 提出一种新型字符串格式化机制,被称为“字符串插值”或者更常见的一种称呼是 F-strings, F-strings提供了一种明确且方便的方式将python表达式嵌入到字符串中来进行格式化:
s1='Hello'
s2='World'
print(f'{s1} {s2}!')
输出结果: Hello World!
在F-strings中我们也可以执行函数:
def power(x):
return x*x
x=4
print(f'{x} * {x} = {power(x)}')
输出结果: 4 * 4 = 16
而且F-strings的运行速度很快,比%-string和str.format()这两种格式化方法都快得多。
总结
以上所述是小编给大家介绍的Python 中字符串拼接的多种方法网站的支持!
来源:https://my.oschina.net/mutoushirana/blog/1861267
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
oracle 存储过程和触发器复制数据
使用python的turtle函数绘制一个滑稽表情
![](https://img.aspxhome.com/file/2023/6/131146_0s.png)
python绘制高斯曲线
![](https://img.aspxhome.com/file/2023/2/107222_0s.jpg)
详解django自定义中间件处理
使用百度云加速后网站打开速度慢、广告不显示的解决方法
![](https://img.aspxhome.com/file/2023/2/112092_0s.png)
对pandas处理json数据的方法详解
![](https://img.aspxhome.com/file/2023/3/69493_0s.jpg)
Python7个爬虫小案例详解(附源码)下篇
![](https://img.aspxhome.com/file/2023/7/86647_0s.png)
Python3.6 之后字典是有序的?
![](https://img.aspxhome.com/file/2023/3/95283_0s.png)
Python制作当年第一款手机游戏-贪吃蛇游戏(练习)
![](https://img.aspxhome.com/file/2023/0/79540_0s.gif)
JS定义函数的几种常用方法小结
Dreamweaver技巧十二招
安装sql server 2008时的4个常见错误和解决方法
![](https://img.aspxhome.com/file/2023/8/98018_0s.png)
使用python怎样产生10个不同的随机数
![](https://img.aspxhome.com/file/2023/7/67927_0s.png)
使用JavaScript构建JSON格式字符串实现步骤
使用Python第三方库发送电子邮件的示例代码
![](https://img.aspxhome.com/file/2023/6/97486_0s.jpg)
python操作日期和时间的方法
关于Vue单页面骨架屏实践记录
![](https://img.aspxhome.com/file/2023/2/126522_0s.png)
vue中自定义指令(directive)的基本使用方法
![](https://img.aspxhome.com/file/2023/2/123192_0s.png)
asp sql去左右空格函数
python 利用jieba.analyse进行 关键词提取
![](https://img.aspxhome.com/file/2023/5/78575_0s.png)