>>> s=['http','://','www','baidu','.com'] 
>>> url=''.join(s) 
>>> url 
'http://wwwbaidu.com' 
>>> 

上面的代码片段是将列表转换成字符串


>>> s=('hello','world','!') 
>>> d=' '.join(s) 
>>> d 
'hello world !' 
>>> 

以上代码片段将元祖转换成字符串


>>> 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']。


注意以下内容:


>>> n=[1,2,3,4] 
>>> s=''.join(n) 
Traceback (most recent call last): 
File " ", line 1, in 
s=''.join(n) 
TypeError: sequence item 0: expected str instance, int found 
>>> 

当列表的值为数字时,不能使用join()方法进行转换字符串,但我们可以通过for循环,将列表中的数字转换成字符串。如下所示:


>>> ss=[1,2,3,4] 
>>> s='' 
>>> for i in ss: 
s += str(i) 
>>> s 
'1234' 

相关文章:

  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
  • 2021-06-18
  • 2022-12-23
  • 2022-03-05
  • 2022-01-30
  • 2021-09-24
猜你喜欢
  • 2021-06-28
  • 2021-06-17
  • 2021-11-05
  • 2021-12-02
  • 2021-11-27
  • 2022-12-23
相关资源
相似解决方案