20190909 Python 练习记录

>>> from io import StringIO
>>> f=StringIO()
>>> f.write('hello')
5
>>> f.write('')
0
>>> f.write(' ')
1
>>> f.write('world')
5
>>> print(f.getvalue())
hello world
>>> f=StringIO('Hello!\nHi!\nGoodbye!')
>>> while True:
    s=f.readline()
    if s == '':
        break
    print(s.strip())
    
Hello!
Hi!
Goodbye!
>>> from io import BytesIO
>>> f=BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
>>> f=BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'
>>> 
>>> import pickle
>>> d=dict(name='bob',age=20,score=88)
>>> pickle.dumps(d)
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x03\x00\x00\x00bobq\x02X\x03\x00\x00\x00ageq\x03K\x14X\x05\x00\x00\x00scoreq\x04KXu.'
>>> f=open('dump.txt','wb')
>>> pickle.dump(d,f)
>>> f.close()
>>> d
{'name': 'bob', 'age': 20, 'score': 88}
>>> import json
>>> d=dict(name='bob',age=20,score=88)
>>> json.dumps(d)
'{"name": "bob", "age": 20, "score": 88}'
>>> json_str='{"age":20,"score":88,"name":"bob"}'
>>> json.loads(json_str)
{'age': 20, 'score': 88, 'name': 'bob'}


import json
def student2dict(std):
    return {
        'name':std.name,
        'age':std.age,
        'score':std.score        
        }
class Student(object):
    def __init__(self,name,age,score):
        self.name=name
        self.age=age
        self.score=score
s=Student('bob',20,99)
print(json.dumps(s,default=student2dict))

import json
class Student(object):
    def __init__(self,name,age,score):
        self.name=name
        self.age=age
        self.score=score
s=Student('bob',20,99)
print(json.dumps(s,default=lambda obj:obj.__dict__))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值