博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Python内置函数之str()

Posted on 2017-08-14 17:38  开飞机的贝塔  阅读(309)  评论(0编辑  收藏  举报

class str(object="")
class str(object=b'', encoding='utf-8', errors='strict')

将其他对象转化为字符串对象。

例子:

>>> str(123)
'123'
>>> str()
''
>>> file = open('data.txt','rb')
>>> fb = file.read()
>>> str(fb)
"b'\\xe5\\xa4\\xa9\\xe7\\x8e\\x8b\\xe7\\x9b\\x96\\xe5\\x9c\\xb0\\xe8\\x99\\x8e\\xef\\xbc\\x8c\\xe5
\\xb0\\x8f\\xe9\\xb8\\xa1\\xe7\\x82\\x96\\xe8\\x98\\x91\\xe8\\x8f\\x87\\xe3\\x80\\x82'"
>>> str(fb,'utf-8') #指定编码集
'天王盖地虎,小鸡炖蘑菇。'
>>> str(fb,'gbk','ignore') #指定报错级别
'澶╃帇鐩栧湴铏庯紝灏忛浮鐐栬槕鑿囥'
>>> file.close()