今天在写python的时候,忽然要将列表中的内容转换成字符串,因而进行了简单的实验,记录下来,方便回忆和使用。python
直接看代码吧:shell
>>> s=['http','://','www','baidu','.com'] >>> url=''.join(s) >>> url 'http://wwwbaidu.com' >>>
上面的代码片断是将列表转换成字符串url
>>> s=('hello','world','!') >>> d=' '.join(s) >>> d 'hello world !' >>>
以上代码片断将元祖转换成字符串code
>>> url='http://www.shein.com' >>> s=url.split('.') >>> s ['http://www', 'shein', 'com'] >>> s=url.split() >>> s ['http://www.shein.com'] >>>
上面代码片断咱们能够看出,经过split()方法,咱们能够将字符串分割成列表,你也能够指定分割的符号,例如上图中,以“.”来进行分割,获得['http://www', 'shein', 'com']。字符串
注意如下内容:it
>>> n=[1,2,3,4] >>> s=''.join(n) Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> s=''.join(n) TypeError: sequence item 0: expected str instance, int found >>>
当列表的值为数字时,不能使用join()方法进行转换字符串,但咱们能够经过for循环,将列表中的数字转换成字符串。以下所示:for循环
>>> ss=[1,2,3,4] >>> s='' >>> for i in ss: s += str(i) >>> s '1234' >>>
以上就是今天记录的所有了,虽然是很小的知识点,但到用时,仍是很容易被忽略的。ast