Python中有join()和os.path.join()两个函数,
具体作用如下:
join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
os.path.join(): 将多个路径组合后返回,语法: os.path.join(path1[,path2[,…]])
1. 字符串转数组
str = '1,2,3,4,5,6'
arr = str.split(',')
print arr#对序列进行操作(分别使用' '与':'作为分隔符)
>>> seq1 = ['hello','good','boy','doiido'] >>> print ' '.join(seq1) hello good boy doiido >>> print ':'.join(seq1) hello:good:boy:doiido
#对字符串进行操作
>>> seq2 = "hello good boy doiido" >>> print ':'.join(seq2) h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
#对元组进行操作
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
#对字典进行操作
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello#合并目录
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'2. 数组转字符串
#方法1
arr = ['a','b'] str1 = ','.join(arr) print str1 # 输出结果: a,b #方法2 arr = [1,2,3] #str = ','.join(str(i) for i in arr)#此处str命名与str函数冲突! str2 = ','.join(str(i) for i in arr) print str2 # 输出结果: 1,2,3
2. 清除字符串前后空格函数的方法
str = ' 2014-04-21 14:10:18 '
str2 = str.strip()
str3 = re.sub(' ','',str)
print str2
print str3
结果如下:
>2014-04-21 14:10:18
>2014-04-2114:10:18