python中的数据类型转化

在符合条件下,python中的字符型,元组,列表,集合,字典等数据类型可以相互转化。

1,字符型--->元组  (str---->tuple,  字符串中每个字符被拆开保存到元组中)

>>> str1 = "This is a new book."
>>> tuple(str1)
(‘T‘, ‘h‘, ‘i‘, ‘s‘, ‘ ‘, ‘i‘, ‘s‘, ‘ ‘, ‘a‘, ‘ ‘, ‘n‘, ‘e‘, ‘w‘, ‘ ‘, ‘b‘, ‘o‘, ‘o‘, ‘k‘, ‘.‘)
>>> str1
‘This is a new book.‘
>>>

2,字符型-->集合(str--->set,字符串中每个字符被拆开,无重复的保存到元组中

>>> set(str1)
{‘T‘, ‘s‘, ‘ ‘, ‘k‘, ‘e‘, ‘a‘, ‘.‘, ‘n‘, ‘i‘, ‘h‘, ‘b‘, ‘w‘, ‘o‘}
>>>

3,字符型--->列表(str--->list,  用list()强转时和元组效果一样,也可以用函数str.split([sep])转化)

>>> list(str1)
[‘T‘, ‘h‘, ‘i‘, ‘s‘, ‘ ‘, ‘i‘, ‘s‘, ‘ ‘, ‘a‘, ‘ ‘, ‘n‘, ‘e‘, ‘w‘, ‘ ‘, ‘b‘, ‘o‘, ‘o‘, ‘k‘, ‘.‘]
>>>

>>> str1  = ‘This is a new book.‘
>>> str1.split()
[‘This‘, ‘is‘, ‘a‘, ‘new‘, ‘book.‘]
>>>

相关推荐