您的位置:首页 > 编程语言 > Python开发

python 之 join的用法

2016-01-14 17:39 369 查看
今天在学习的时候,发现一段代码

执行压缩文件的时候

source_name = "sys_bak.tar.gz"

source_dir = ["/etc","/boot","/var/www/html"]

tar_cmd = "tar zcvf %s %s " %(source_name, ' '.join(source_dir))

始终没有理解 ' '.join(soure_dir)在这里的用法

经过一番研究,终于搞明白了。之前一直和 split函数搞混了,一直模糊的认为是join可转换为list,其实不然是split函数。

>:这就是看书不认真导致

a.split("") 是可以将str -----> list

如:

>>> a = "thx for you"
>>> type (a)
<type 'str'>

>>> a.split(" ")
['thx', 'for', 'you']
>>> type(a)
<type 'str'>
>>> c = a.split(" ")
>>> type(c)
<type 'list'>

而 join可以说是 split的逆运算

如:

>>> word = ["/abc","/def","/ghi"]

>>> word_str = ' '.join(word)
>>> print word_str
/abc /def /ghi

>>> type(word_str)
<type 'str'>

再来一个:

>>> data = [1,2,3,4,5]
>>> data_str = ' '.join(data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found

为什么到这里就不行了呢

因为join转换之后,就成了 1,2,3,4,5 而本身1,2,3,4,5是int类型的

>>> data_other = ["1","2","3","4"]
>>> data_ostr = ' '.join(data_other)

>>> type(data_ostr)
<type 'str'>
>>> print data_ostr
1 2 3 4

这样是不是就ok了呢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: