2022年 11月 4日

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

推荐简单实用方法:
一、str1+str2
二、格式化连接
三、jion连接


一. str1+str2

string 类型 ‘+’号连接

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

二. 格式化字符串连接

string 类型格式化连接

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

三. 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'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

这里的 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

四. 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

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

>>> str1="one"
>>> str2="two"
>>> str1 ,str2
('one', 'two')
>>> type((str1 ,str2))
<type 'tuple'>
>>>
  • 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

七. Mstr1N

string 类型乘法连接

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

八. 列表推导方式连接

与 join 方式类似

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