python list,str操作

一、str转换为list

<list> = <str>.split(<separator>)

<str>: 需要进行分隔提取的字符串 
<separator>:从<str2>提取元素时依据的分隔符,一般也是一个str类型,如',' 
<list>: 返回值,list中每个元素是<str>中分隔后的一个片段

str1 = "12345"
list1 = list(str1)
print list1
 
str2 = "123 sjhid dhi"
list2 = str2.split() #or list2 = str2.split(" ")
print list2
 
str3 = "www.google.com"
list3 = str3.split(".")
print list3
 
#输出为:
 
['1', '2', '3', '4', '5']
['123', 'sjhid', 'dhi']
['www', 'google', 'com']

二、list转换为str

<str> = <separator>.join(<list>)

<separator>: 分隔符,为str类型,如',' 
<list>: 需要进行合并的list对象,其中每个元素必须为str类型 
<str>: 返回一个str对象,是将<list>中每个元素按顺序用分隔符<separator>拼接而成

str4 = "".join(list3)
print str4
str5 = ".".join(list3)
print str5
str6 = " ".join(list3)
print str6
#输出为:
wwwgooglecom
www.google.com
www google com

三.list的拼接

python合并list有几种方法: 
1 .append() 向列表尾部追加一个新元素,列表只占一个索引位,在原有列表上增加 
2 .extend() 向列表尾部追加一个列表,将列表中的每个元素都追加进来,在原有列表上增加 
3 .+ 直接用+号看上去与用extend()一样的效果,但是实际上是生成了一个新的列表存这两个列表的和,只能用在两个列表相加上 
4 .+= 效果与extend()一样,向原列表追加一个新元素,在原有列表上增加

例: 
1、append,向列表尾部追加一个新元素,列表只占一个索引位,在原有列表上增加

a=[1,2,3]
b=[9,8,7]

test=a.append(b)
print(a)        #[1, 2, 3, [9, 8, 7]]
print(test)     #None

2、extend 向列表尾部追加一个列表,将列表中的每个元素都追加进来,在原有列表上增加

a=[1,2,3]
b=[9,8,7]

test=a.extend(b)
print(a)        #[1, 2, 3, 9, 8, 7]
print(test)     #None

3 + 直接用+号看上去与用extend()一样的效果,但是实际上是生成了一个新的列表存这两个列表的和,只能用在两个列表相加上

a=[1,2,3]
b=[9,8,7]

test=a+b
print(a)        #[1, 2, 3]
print(test)     #[1, 2, 3, 9, 8, 7]

4 .+= 效果与extend()一样,向原列表追加一个新元素,在原有列表上增加

a=[1,2,3]
b=[9,8,7]

a+=b
print(a)        #[1, 2, 3, 9, 8, 7]

四、字符串的拼接 

Python字符串拼接的几种方法:

1、str1 + str2

    我想大多数人都会使用+号来进行字符串的拼接;   eg  :    'wbz' + 'ctt'='wbzctt'

2、str1,str2

    这种方式就有点特殊了,如果两个字符串用逗号隔开,那仫这两个字符串就会被拼接,但是拼接之后的新的字符串中间会存在空格;  eg  :  'wbz','ctt'='wbz ctt'

3、str1 str2

   这种拼接方式是Python独有的,只要将两个字符串放在一起,这两个字符串就会自动拼接成新的字符串,不管这两个字符串中间是否存在空格;       eg  :  'wbz''ctt'='wbzctt'           'wbz' 'ctt'='wbzctt'

4、%连接字符串  

   这种方式相对于其他的拼接方式来说就有些强大了,因为它借鉴了C语言中printf()函数的功能。这种方式用符号'%'连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换;      eg  :  '%s %s' % ('wbz','ctt') = 'wbz ctt'

5、字符串列表连接  str.join(list)

   这个函数join接受一个列表,燃用用字符串连接列表中的每一个元素;

data = ['wbz','ctt','Python']
str = '@@@'
str.join(data) = 'wbz@@@ctt@@@Python'


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

>>> list1
['a', 'b', 'c']
>>> "".join(list1)
'abc'
>>> type("".join(list1))
<type 'str'>
>>>

参考自:

https://blog.csdn.net/roytao2/article/details/53433373

https://blog.csdn.net/oneday_789/article/details/79056788

https://blog.csdn.net/Keeplingshi/article/details/72667582

猜你喜欢

转载自blog.csdn.net/weixin_38383877/article/details/82380995