zoukankan      html  css  js  c++  java
  • python 字符串、列表和元祖之间的切换

    >>> 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' 
  • 相关阅读:
    安装oracle常见问题和解决方案
    配置VNC
    爬虫
    启动Tomcat报异常host-manager does not exist or is not a readable directory
    linux升级openssl
    linux6的yum源
    linux升级openssh
    linux操作oracle
    Linux 系统结构
    Linux MD5值递归比对目录中的文件是否有修改
  • 原文地址:https://www.cnblogs.com/MisterZZL/p/9534302.html
Copyright © 2011-2022 走看看