Python中的列表,元组,字符串之间的相互转化

2023-10-15,,

  Python中的列表元组和字符串之间的相互转化需要利用,tuple(),list(),str().

示例如下:

>>> the_string = "hello I'am xiaoli!"
>>> #字符串转化为元组
>>> the_tuple = tuple(the_string)
>>> the_tuple
('h', 'e', 'l', 'l', 'o', ' ', 'I', "'", 'a', 'm', ' ', 'x', 'i', 'a', 'o', 'l', 'i', '!')
>>> #字符串转化为列表
>>> the_list = list(the_string)
>>> the_list
['h', 'e', 'l', 'l', 'o', ' ', 'I', "'", 'a', 'm', ' ', 'x', 'i', 'a', 'o', 'l', 'i', '!']
>>> #元组转化为列表
>>> the_list = list(the_tuple)
>>> the_list
['h', 'e', 'l', 'l', 'o', ' ', 'I', "'", 'a', 'm', ' ', 'x', 'i', 'a', 'o', 'l', 'i', '!']>>> the_tuple = tuple(the_list)
>>> the_tuple
('h', 'e', 'l', 'l', 'o', ' ', 'I', "'", 'a', 'm', ' ', 'x', 'i', 'a', 'o', 'l', 'i', '!')
>>> #如果将元组和列表转化为字符串需要join()
>>> "".join(the_tuple)
"hello I'am xiaoli!"
>>> "".join(the_list)
"hello I'am xiaoli!"
>>> #如果不用join()函数
>>> str(the_tuple)
'(\'h\', \'e\', \'l\', \'l\', \'o\', \' \', \'I\', "\'", \'a\', \'m\', \' \', \'x\', \'i\', \'a\', \'o\', \'l\', \'i\', \'!\')'

总结一点:join是连接字符的重要方法。

Python中的列表,元组,字符串之间的相互转化的相关教程结束。

《Python中的列表,元组,字符串之间的相互转化.doc》

下载本文的Word格式文档,以方便收藏与打印。