>> str2="two" >>> str1+str2 'onetwo' >>> 二.">

Python连接字符串的8种方法汇总

Python连接字符串的8种方法汇总

推荐简单实用方法:

一、str1+str2

二、格式化连接

三、jion连接

一. str1+str2

string 类型 ‘+’号连接

>>> str1="one"

>>> str2="two"

>>> str1+str2

'onetwo'

>>>

二. 格式化字符串连接

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

三. join 方式连接

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

>>> str1="--"

>>> str2="one"

>>> list1=["a","b","c"]

>>> tuple1=("H","I","J")

>>> str1.join(list1)

'a--b--c'

>>> str2.join(tuple1)

'HoneIoneJ'

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

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

>>> list2=["a",2,"c",4.3]

>>> str1.join(list2)

Traceback (most recent call last):

File "", line 1, in

TypeError: sequence item 1: expected string, int found

>>>

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

>>> list1

['a', 'b', 'c']

>>> "".join(list1)

'abc'

>>> type("".join(list1))

>>>

四. str1 str2

string 类型空格自动连接

>>> "one" "two"

'onetwo'

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

错误方式:

>>> str1="one"

>>> str2="two"

>>> str1 str2

File "", line 1

str1 str2

^

SyntaxError: invalid syntax

五. str1,str2

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

>>> str1="one"

>>> str2="two"

>>> str1 ,str2

('one', 'two')

>>> type((str1 ,str2))

>>>

六. str1 \ str2 \str3

string 类型反斜线多行连接

>>> test = "str1 " \

... "str2 " \

... "str3"

>>> test

'str1 str2 str3'

>>>

七. Mstr1N

string 类型乘法连接

>>> str1="one"

>>> 1*str1*4

'oneoneoneone'

>>>

八. 列表推导方式连接

与 join 方式类似

>>> "".join(["Land" for i in xrange(3)])

'LandLandLand'

>>> "0".join(["Land" for i in xrange(2)])

'Land0Land'

>>>

相关推荐

手机声音录制全攻略:从自带功能到第三方软件,轻松掌握
导览七月的日本
365 双式投注

导览七月的日本

📅 08-10 🔥 177
共享电单车项目的投资费用是多少
365三式投注

共享电单车项目的投资费用是多少

📅 08-05 🔥 231
偷偷混入包养群,发现富婆们在线烤鸭
365 双式投注

偷偷混入包养群,发现富婆们在线烤鸭

📅 09-11 🔥 618
青云哪个级别武器外观好看
365三式投注

青云哪个级别武器外观好看

📅 08-14 🔥 325
夏天稀饭能放多长时间
365三式投注

夏天稀饭能放多长时间

📅 09-02 🔥 537