python 列表 字典 string 互相转换
2014-09-16 21:52
721 查看
1: dict 转为 string 使用str方法
2: string 转为 dict 使用eval方法
3: list 转为string 使用join方法, 单引号内为字符连接的符号, 可以为空,也可以为 '-' 等符号
4: string 转为 list 这个就很方便了,使用split函数,参数为分隔符,可以为空
关于string前面的u, 在python2.x中,对字符的兼容还不是很好, 使用3.x 问题不大. 养成一个良好的习惯, 在string前面加一个u, 会省去很多编码问题. 如果你有编码问题,可以参阅这篇文章,写的很好.
python 编码问题注意点
<span style="font-size:18px;">a = {1: 'a', 2: 'b'} a = str(a) print a, type(a) ----- {1: 'a', 2: 'b'} <type 'str'></span>
2: string 转为 dict 使用eval方法
<span style="font-size:18px;">a = "{1: 'a', 2: 'b'}" a = eval(a) print a, type(a) ------ {1: 'a', 2: 'b'} <type 'dict'></span>
3: list 转为string 使用join方法, 单引号内为字符连接的符号, 可以为空,也可以为 '-' 等符号
<span style="font-size:18px;">a = ['hello', 'world'] b = ' '.join(a) print b, type(b) c= '-'.join(a) print c, type(c) ---- hello world <type 'str'> hello-world <type 'str'></span>
4: string 转为 list 这个就很方便了,使用split函数,参数为分隔符,可以为空
<span style="font-size:18px;">a = u'hello world' b = a.split(' ') print b, type(b) c = a.split('o') print c, type(c) ------- [u'hello', u'world'] <type 'list'> [u'hell', u' w', u'rld'] <type 'list'></span>
关于string前面的u, 在python2.x中,对字符的兼容还不是很好, 使用3.x 问题不大. 养成一个良好的习惯, 在string前面加一个u, 会省去很多编码问题. 如果你有编码问题,可以参阅这篇文章,写的很好.
python 编码问题注意点
相关文章推荐
- Python字符串、元组、列表、字典互相转换的方法
- python的字典、列表于字符串的互相转换
- Python字符串、元组、列表、字典互相转换的方法
- python基础学习——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- Python字符串、元组、列表、字典互相转换的方法
- Python字符串、元组、列表、字典互相转换的方法
- 【知识】Python中字符串、元组、列表、字典的互相转换
- python基础数据结构——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- python3中bytes与string的互相转换
- python列表,元组,字典和字符串之间的相互转换
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- python中列表,元组,字符串 互相转换
- python中列表,元组,字符串如何互相转换
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- python3中bytes与string的互相转换
- python3中bytes与string的互相转换
- 转--Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- python中列表,元组,字符串互相转换
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- python 字符串,元组, 列表,字典之间的转换