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了呢
执行压缩文件的时候
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了呢
相关文章推荐
- RevitAPI: Revit 2016里的Python代码例子Sample code
- [Leetcode]@python 73. Set Matrix Zeroes
- Python -- 写Excel文件
- Python 2.5.13 装饰器
- [Leetcode]@python 72. Edit Distance
- Elasticsearch介绍,单机安装,python 写Elasticsearch API
- Python文件处理
- python os的一些用法(-)
- Python 进阶 - 正则表达式
- python2.79安装
- 目录克隆(拷贝)
- 批量反编译和重新编译签名 Python脚本(附源代码)
- Python工程师面试题 与Python基础语法相关
- 将列表传递给函数
- Python -- 三元表达式(三目运算符)
- python SMTP 发送邮件
- python实现二叉树
- PEP8 Python 编码规范整理
- [Leetcode]@python 71. Simplify Path
- Python 大小写转换