python列表以指定字符串间隔转成字符串两种方法:
第一种:
join()方法:
代码:
a = ['a','b','c']
c = ','
b = c.join(a)
print(b)
结果:a,b,c
注意:
列表内元素必须是字符类型不能是整数类型,否则会报错:TypeError: sequence item 0: expected str instance, int found
如图:
第二种方法:、
>>> a = ['a','b','c']
>>> b = '%s'*len(a) %(tuple(a))
>>> print(b)
abc
解释:
将列表转换成元组, '%s'*len(a)这里等同于%s%s%s,len()是得到列表长度,例如列表有10个数据就是%s%s%s%s%s%s%s%s%s%s
延伸:
不是说可以以指定的字符串间隔么?那第二种方法怎么没有间隔符存在呢?
代码:
>>> a = ['a','b','c']
>>> b = '%s-'*len(a) %(tuple(a))
>>> print(b)
a-b-c-
>>> jiange = '%s-'
>>> b = jiange*len(a) %(tuple(a))
>>> print(b)
a-b-c-
>>> jiange = '-'
>>> b = '%s'jiange*len(a) %(tuple(a))
SyntaxError: invalid syntax
>>> b = '%s'+jiange*len(a) %(tuple(a))
Traceback (most recent call last):
File "", line 1, in
b = '%s'+jiange*len(a) %(tuple(a))
TypeError: not all arguments converted during string formatting
>>> b = str('%s'+jiange)*len(a) %(tuple(a))
>>> print(b)
a-b-c-
>>>
如下图思考:
来自Davids zhou博客原创文章请尊重作者:http://www.zongk.com/zongk/91.html转载请标注此链接