脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现string字符串连接的方法总结【8种方式】

Python实现string字符串连接的方法总结【8种方式】

2021-03-13 00:38LandGrey Python

这篇文章主要介绍了Python实现string字符串连接的方法,结合实例形式总结分析了Python实现字符串连接的8种常见操作技巧,需要的朋友可以参考下

本文实例总结了Python实现string字符串连接的方法。分享给大家供大家参考,具体如下:

以下基于python 2.7版本,代码片段真实有效。

一. str1+str2

string类型 ‘+'号连接

?
1
2
3
4
5
>>> str1="one"
>>> str2="two"
>>> str1+str2
'onetwo'
>>>

二. str1,str2

string类型 ‘,'号连接成tuple类型

?
1
2
3
4
5
6
7
>>> str1="one"
>>> str2="two"
>>> str1 ,str2
('one', 'two')
>>> type((str1 ,str2))
<type 'tuple'>
>>>

三. 格式化字符串连接

string类型格式化连接

1.常见的格式化方式

?
1
2
3
4
>>> str1="one"
>>> str2="two"
>>> "%s%s"%(str1,str2)
'onetwo'

2.高级点的format 格式化

?
1
2
>>> "{test}_666@{data:.2f}".format(test="Land", data=10.1)
'Land_666@10.10'

3.鲜为人知的【%(word)typeprint函数格式化

?
1
2
>>> print "%(test)s666%(last)d" % {"test": "Land", "last": 101}
Land666101

四. str1 str2

string类型空格自动连接

?
1
2
>>> "one" "two"
'onetwo'

这里需要注意的是,参数不能代替具体的字符串写成
错误方式:

?
1
2
3
4
5
6
7
>>> str1="one"
>>> str2="two"
>>> str1 str2
 File "<stdin>", line 1
  str1 str2
      ^
SyntaxError: invalid syntax

五. str1 \ str2 \str3

string类型反斜线多行连接

?
1
2
3
4
5
6
>>> test = "str1 " \
... "str2 " \
... "str3"
>>> test
'str1 str2 str3'
>>>

六. M*str1*N

string类型乘法连接

?
1
2
3
4
>>> str1="one"
>>> 1*str1*4
'oneoneoneone'
>>>

七. join方式连接

string类型join方式连接list/tuple类型

?
1
2
3
4
5
6
7
>>> str1="one"
>>> list1=["a","b","c"]
>>> tuple1=("H","I","J")
>>> str1.join(list1)
'aonebonec'
>>> str1.join(tuple1)
'HoneIoneJ'

这里的join有点像split的反操作,将列表或元组用指定的字符串相连接;

但是值得注意的是,连接的列表或元组中元素的类型必须全部为string类型,否则就可能报如下的错误:

?
1
2
3
4
5
6
>>> list2=["a",2,"c",4.3]
>>> str1.join(list2)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected string, int found
>>>

join还有一个妙用,就是将所有list或tuple中的元素连接成string类型并输出;

?
1
2
3
4
5
6
7
>>> list1
['a', 'b', 'c']
>>> "".join(list1)
'abc'
>>> type("".join(list1))
<type 'str'>
>>>

八.列表推导方式连接

与join方式类似

?
1
2
3
4
5
>>> "".join(["Land" for i in xrange(3)])
'LandLandLand'
>>> "0".join(["Land" for i in xrange(2)])
'Land0Land'
>>>

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/c465869935/article/details/52160445

延伸 · 阅读

精彩推荐