replace函数在python2中编码格式的转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangfengling1023/article/details/82663360

在python2版本中处理字符串时,经常能遇到的问题就是编码格式问题,一不小心就会遇到问题

今天偶然间发现replace()函数可以将字符串的编码格式进行更改,具体的代码如下所示:

>>> a = 'hello a'
>>> print type(a)
<type 'str'>
>>> b = u'hello b'
>>> print type(b)
<type 'unicode'>
>>> c = b.replace(u'',u'')
>>> c
u'hello b'
>>> print type(b)
<type 'unicode'>
>>> d = a.replace(u'',u'')
>>> d
u'hello a'
>>> print type(a)
<type 'str'>
>>> print type(d)
<type 'unicode'>
>>>

 当a字符串是str类型时,使用replace(u'',u'')虽然操作之后什么内容也没有进行更改,但在无形当中将字符串的编码格式由str变为unicode

这把操作我服了。。。。。

但试了一下在python3中不会出现上面的情况,在python3中代码如下所示:

>>> str2 = u'he'
>>> print(type(str2))
<class 'str'>
>>> a = str2.replace(u'',u'')
>>> print(type(a))
<class 'str'>

如果你也遇到python中的小坑,可以交流一下

猜你喜欢

转载自blog.csdn.net/yangfengling1023/article/details/82663360
今日推荐