python中 join和split的使用

今天学习codecademy的python课程的时候,遇到了join和split的使用。一开始不知道用,后来google了一下才知道。

1
2
str.join(iterable): Return a string which is the concatenation of the strings in the iterable iterable.
The separator between elements is the string providing this method.

简单的说,join就是在譬如list中,在每个元素之间加入特定的字符串让它们连接起来,然后返回字符串。

1
2
3
4
5
>>>li = ['My', 'name', 'is', 'kagami']
>>>print " ".join(li)
My name is kagami
>>>print "+".join(li)
My+name+is+kagami

split刚好相反,它是将字符串用特定字符串作为标志分隔成一个个元素,返回元素的list

1
2
3
>>>li = 'My name is kagami'
>>>print li.split(" ")
['My', 'name', 'is', 'kagami']