首先介绍一下python2和python3的字符串区别
python2中字符串前面加u代表是unicode类型字符串
python3中字符串前面是否有u都是str类型
[root@优快云 ~]#python2
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = '{"name":"哈利破特"}'
>>> name_u = u'{"name":"哈利破特"}'
>>> print(type(name), type(name_u))
(<type 'str'>, <type 'unicode'>)
>>>
[root@优快云 ~]#python3
Python 3.6.8 (default, May 26 2019, 10:58:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> name = '{"name":"哈利破特"}'
>>> name_u = u'{"name":"哈利破特"}'
>>> print(type(name), type(name_u))
<class 'str'> <class 'str'>
>>>
字符串转dict类型
>>> name_dict = eval(name)
>>> type(name_dict)
<class 'dict'>
>>> name_dict['name']
'哈利破特'
>>>
本文介绍了Python2和Python3中字符串的区别,Python2的字符串类型分为普通str和unicode,而Python3所有字符串都是str类型。此外,演示了如何将字符串转换为字典类型,通过使用`eval()`函数可以将格式化的字符串转化为字典,方便数据操作。
673

被折叠的 条评论
为什么被折叠?



