列表,元组,字符串互相转换

列表,元组,字符串之间的转化通过join(), str(), list(), tuple() 这四个函数实现。

  • 用list可以把字符串和元组转化为列表

    >>> demo_str = 'test' 
    >>> demo_tuple = ('t','e','s','t')
    >>>demo_list = ['t','e','s','t']
    >>> temp = list(demo_tuple)
    >>> type(temp)
    <type 'list'>
    >>> temp = list(demo_str)
    >>> type(temp)
    <type 'list'>
    
  • 用tuple() 可以将字符串和列表转化为元组

    >>> demo_str = 'test' 
    >>> demo_tuple = ('t','e','s','t')
    >>>demo_list = ['t','e','s','t']
    >>> temp = tuple(demo_str)
    >>> type(temp)
    <type 'tuple'>
    >>> temp = tuple(demo_list)
    >>> type(temp)
    <type 'tuple'>
    
  • 用str() 可以将字符串和列表转化为字符串
    >>> demo_str = 'test' 
    >>> demo_tuple = ('t','e','s','t')
    >>>demo_list = ['t','e','s','t']
    >>> temp = str(demo_list)
    >>> type(temp)
    <type 'str'>
    >>> temp = str(demo_tuple)
    >>> type(temp)
    <type 'str'>
    

注意

用str()转换的字符串不能用print()函数以字符串形式显示

>>> demo_str = ‘test’
>>> demo_tuple = (‘t’,’e’,’s’,’t’)
>>>demo_list = [‘t’,’e’,’s’,’t’]
>>> temp = str(demo_list)
>>> type(temp)
<type ‘str’>
>>>print (temp)
[‘t’, ‘e’, ‘s’, ‘t’]
>>> temp = str(demo_tuple)
>>> type(temp)
<type ‘str’>
>>>print (temp)
(‘t’, ‘e’, ‘s’, ‘t’)

对于这种问题要用join()函数处理

>>> demo_str = ‘test’
>>> demo_tuple = (‘t’,’e’,’s’,’t’)
>>>demo_list = [‘t’,’e’,’s’,’t’]
>>> temp = ‘’.join(demo_list)
>>> type(temp)<type ‘str’>
>>>print (temp)
test
>>> temp = ‘’.join(demo_tuple)
>>> type(temp)
<type ‘str’>
>>>print (temp)
test

用join()和str()生成的都是字符串类型的,但为什么用print 输出的结果不同?

 


本文地址: http://blog.0x7c00.cn/?p=179 By Breaker

同时被收录在: Breaker’s Wiki QQ: 791628659