美文网首页
Python 字符串str和列表 list互转

Python 字符串str和列表 list互转

作者: 步履不停的Suunny | 来源:发表于2018-07-10 15:20 被阅读0次

    字符串和list互转

    str to list:

    >>> str = "123456"
    >>> list(str)
    ['1', '2', '3', '4', '5', '6']
    
    >>> str2 = "123 abc hello" 
    >>> str2.split()           #按空格分割成字符串
    ['123', 'abc', 'hello']
    

    或者

    >>> str2.split(" ")
    ['123', 'abc', 'hello']
    

    list to str:

    方法: ''.john(list)

    如:

    >>> list = ['a','b','c']
    >>> ''.join(list)
    'abc'
    

    另外:

    >>> lst = [1, 2, 3, 4, 5]
    >>> ''.join(lst)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: sequence item 0: expected str instance, int found
    >>>
    >>> ''.join(str(s) for s in lst)      #修改lst中的元素为str
    '12345'
    
    >>> ls = [1,2,3,None,"NULL"]
    >>> print (','.join(str(s) for s in ls if s not in [None,"NULL"]))
    1,2,3
    

    参考链接:
    https://www.cnblogs.com/justdo-it/articles/8297303.html

    相关文章

      网友评论

          本文标题:Python 字符串str和列表 list互转

          本文链接:https://www.haomeiwen.com/subject/stafpftx.html