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

yipeiwu_com5年前Python基础

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

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

一. str1+str2

string类型 ‘+'号连接

>>> str1="one"
>>> str2="two"
>>> str1+str2
'onetwo'
>>>

二. str1,str2

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

>>> str1="one"
>>> str2="two"
>>> str1 ,str2
('one', 'two')
>>> type((str1 ,str2))
<type 'tuple'>
>>>

三. 格式化字符串连接

string类型格式化连接

1.常见的格式化方式

>>> str1="one"
>>> str2="two"
>>> "%s%s"%(str1,str2)
'onetwo'

2.高级点的format 格式化

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

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

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

四. str1 str2

string类型空格自动连接

>>> "one" "two"
'onetwo'

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

>>> str1="one"
>>> str2="two"
>>> str1 str2
 File "<stdin>", line 1
  str1 str2
      ^
SyntaxError: invalid syntax

五. str1 \ str2 \str3

string类型反斜线多行连接

>>> test = "str1 " \
... "str2 " \
... "str3"
>>> test
'str1 str2 str3'
>>>

六. M*str1*N

string类型乘法连接

>>> str1="one"
>>> 1*str1*4
'oneoneoneone'
>>>

七. join方式连接

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程序设计有所帮助。

相关文章

python海龟绘图实例教程

本文以实例形式介绍了python turtle模块即海龟绘图的使用方法,对于需要进行图形编程的朋友相信会有一定的借鉴价值。 python turtle模块简介:  python...

详解如何用TensorFlow训练和识别/分类自定义图片

详解如何用TensorFlow训练和识别/分类自定义图片

很多正在入门或刚入门TensorFlow机器学习的同学希望能够通过自己指定图片源对模型进行训练,然后识别和分类自己指定的图片。但是,在TensorFlow官方入门教程中,并无明确给出如何...

python pandas中对Series数据进行轴向连接的实例

有时候我们想要的数据合并结果是数据的轴向连接,在pandas中这可以通过concat来实现。操作的对象通常是Series。 Ipython中的交互代码如下: In [17]: fro...

pandas的连接函数concat()函数的具体使用方法

pandas的连接函数concat()函数的具体使用方法

concat()函数的具体用法 pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,...

python发送邮件实例分享

python发送邮件实例分享

为了更好的理解邮件发送功能的实现,要先了解邮件发送系统的大致流程。首先  电子邮件之间的相互发送接受就像  邮局邮件发送一样,从一个站点(邮件发送服务器)到目的地站点...