本文实例总结了Python实现string字符串连接的方法。分享给大家供大家参考,具体如下:
以下基于python 2.7版本,代码片段真实有效。
string类型 ‘+'号连接
>>> str1="one"
>>> str2="two"
>>> str1+str2
'onetwo'
>>>
string类型 ‘,'号连接成tuple类型
>>> str1="one"
>>> str2="two"
>>> str1 ,str2
('one', 'two')
>>> type((str1 ,str2))
<type 'tuple'>
>>>
string类型格式化连接
>>> str1="one"
>>> str2="two"
>>> "%s%s"%(str1,str2)
'onetwo'
format
格式化>>> "{test}_666@{data:.2f}".format(test="Land", data=10.1)
'Land_666@10.10'
%(word)type
】print
函数格式化>>> print "%(test)s666%(last)d" % {"test": "Land", "last": 101}
Land666101
string类型空格自动连接
>>> "one" "two"
'onetwo'
这里需要注意的是,参数不能代替具体的字符串写成
错误方式:
>>> str1="one"
>>> str2="two"
>>> str1 str2
File "<stdin>", line 1
str1 str2
^
SyntaxError: invalid syntax
string类型反斜线多行连接
>>> test = "str1 " \
... "str2 " \
... "str3"
>>> test
'str1 str2 str3'
>>>
string类型乘法连接
>>> str1="one"
>>> 1*str1*4
'oneoneoneone'
>>>
string类型join方式连接list/tuple类型
>>> str1="one"
>>> list1=["a","b","c"]
>>> tuple1=("H","I","J")
>>> str1.join(list1)
'aonebonec'
>>> str1.join(tuple1)
'HoneIoneJ'
这里的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
>>>
join还有一个妙用,就是将所有list或tuple中的元素连接成string类型并输出;
>>> list1
['a', 'b', 'c']
>>> "".join(list1)
'abc'
>>> type("".join(list1))
<type 'str'>
>>>
与join方式类似
>>> "".join(["Land" for i in xrange(3)])
'LandLandLand'
>>> "0".join(["Land" for i in xrange(2)])
'Land0Land'
>>>
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。