您的位置:首页 > 编程语言 > Python开发

python string字符串的8种连接方式

2018-01-18 09:51 507 查看
以下基于python 2.7版本,代码片段真实有效。

一. str1+str2

string类型 ‘+’号连接
>>> str1="one"
>>> str2="two"
>>> str1+str2
'onetwo'
>>>
1
2
3
4
5

二. str1,str2

string类型 ‘,’号连接成tuple类型
>>> str1="one"
>>> str2="two"
>>> str1 ,str2
('one', 'two')
>>> type((str1 ,str2))
<type 'tuple'>
>>>
1
2
3
4
5
6
7

三. 格式化字符串连接

string类型格式化连接1.常见的格式化方式
>>> str1="one"
>>> str2="two"
>>> "%s%s"%(str1,str2)
'onetwo'
1
2
3
4
2.高级点的format 格式化
>>> "{test}_666@{data:.2f}".format(test="Land", data=10.1)
'Land_666@10.10'
1
2
3.鲜为人知的【%(word)type】print函数格式化
>>> print "%(test)s666%(last)d" % {"test": "Land", "last": 101}
Land666101
1
2

四. str1 str2

string类型空格自动连接
>>> "one" "two"
'onetwo'
1
2
这里需要注意的是,参数不能代替具体的字符串写成 
错误方式:
>>> str1="one"
>>> str2="two"
>>> str1 str2
File "<stdin>", line 1
str1 str2
^
SyntaxError: invalid syntax
1
2
3
4
5
6
7

五. str1 \ str2 \str3

string类型反斜线多行连接
>>> test = "str1 " \
... "str2 " \
... "str3"
>>> test
'str1 str2 str3'
>>>
1
2
3
4
5
6

六. M*str1*N

string类型乘法连接
>>> str1="one"
>>> 1*str1*4
'oneoneoneone'
>>>
1
2
3
4

七. join方式连接

string类型join方式连接list/tuple类型
>>> str1="one"
>>> list1=["a","b","c"]
>>> tuple1=("H","I","J")
>>> str1.join(list1)
'aonebonec'
>>> str1.join(tuple1)
'HoneIoneJ'
1
2
3
4
5
6
7
这里的join有点像split的反操作,将列表或元组用指定的字符串相连接; 
但是值得注意的是,连接的列表或元组中元素的类型必须全部为string类型,否则就可能报如下的错误:
>>> 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
>>>
1
2
3
4
5
6
join还有一个妙用,就是将所有list或tuple中的元素连接成string类型并输出;
>>> list1
['a', 'b', 'c']
>>> "".join(list1)
'abc'
>>> type("".join(list1))
<type 'str'>
>>>
1
2
3
4
5
6
7

八.列表推导方式连接

与join方式类似
>>> "".join(["Land" for i in xrange(3)])
'LandLandLand'
>>> "0".join(["Land" for i in xrange(2)])
'Land0Land'
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: