python字符串拼接
python,字符串,拼接
2025-04-07 09:01:22 时间
大家好,又见面了,我是你们的朋友全栈君。
Python字符串拼接
在Python的实际开发中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天总结一下:
- 用
+
符号拼接 - 用
%
符号拼接 - 用
join()
方法拼接 - 用
format()
方法拼接 - 用
string
模块中的Template
对象
如果还有其他方法,欢迎补充。 例子:
fruit1 = 'apples'
fruit2 = 'bananas'
fruit3 = 'pears'
要求: 输出字符串’There are apples, bananas, pears on the table’
1. 用+
符号拼接
用+
拼接字符串如下:
1 str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table'
该方法效率比较低,不建议使用
2. 用%
符号拼接
用%
符号拼接方法如下:
1 str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3)
除了用元组的方法,还可以使用字典如下:
1 str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % {'fruit1':fruit1,'fruit2':fruit2,'fruit3':fruit3}
该方法比较通用
3. 用join()
方法拼接
join()`方法拼接如下
1 temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table']
2 ''.join(temp)
该方法使用与序列操作
4. 用format()
方法拼接
用format()
方法拼接如下:
4. 用format()
方法拼接
用format()
方法拼接如下:
1 str = 'There are {}, {}, {} on the table'
2 str.format(fruit1,fruit2,fruit3)
还可以指定参数对应位置:
1 str = 'There are {2}, {1}, {0} on the table'
2 str.format(fruit1,fruit2,fruit3) #fruit1出现在0的位置
同样,也可以使用字典:
1 str = 'There are {fruit1}, {fruit2}, {fruit3} on the table'
2 str.format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3)
5. 用string
模块中的Template
对象
用string
模块中的Template
对象如下:
1 from string import Template
2 str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table') #此处用的是{},别搞错了哦
3 str.substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) #如果缺少参数,或报错如果使用safe_substitute()方法不会
4 str.safe_substitute(fruit1=fruit1,fruit2=fruit2)
5 #输出'There are apples, bananas, ${fruit3} on the table'
总结
拼接的方法有多种,不同场合下使用不同的方法,个人比较推荐%
、format()
方法,简单方便。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/155949.html原文链接:https://javaforall.cn
相关文章
- Python数据库同步神器(一键同步)
- 二分查找(非递归、递归)python实现
- Python-正则匹配
- python的第三方库是用什么实现的_python 第三方库
- python 四大基础数据结构及操作
- Python怎么输入小数和整数_python输入非负整数
- python中griddata的外插值_利用griddata进行二维插值
- python进制转换函数-Python中进制转换函数的使用
- 【Python问题解决】---- RecursionError: maximum recursion depth exceeded while calling a Python object
- 2022年最新Python大数据之Python基础【九】面向对象与继承
- 知乎高赞!有没有适合新手练习 Python 的做题类网站?
- 用Python画个生日蛋糕为朋友庆生
- Python基本数据类型-字符型
- 240个Python练习案例附源码(百看不如一练)
- Python 图_系列之纵横对比 Bellman-Ford 和 Dijkstra 最短路径算法
- Python 二进制,十进制,十六进制转换「建议收藏」
- python lambda表达式详解_lambda python
- java异或运算符_python 异或
- pyinstaller打包python-docx报错 No such file or directory (default-header.xml)
- 羊了个羊,但是Python简(li)单(pu)版