python str与bytes之间的转换

来源:互联网 发布:阿里云 香港机房 被墙 编辑:程序博客网 时间:2024/05/16 09:58

今天用python调用windows api的时候出了点问题,ctypes.c_char_p()这个函数,只接受bytes型或是int型的数据,但是我的传入参数却是str类型的,所以需要把str转换成bytes型的。

转换的方法如下:

    bytes object   b = b"example"       str object   s = "example"        #str to bytes       bytes(s, encoding = "utf8")       #bytes to str       str(b, encoding = "utf-8")      #an alternative method       #str to bytes       str.encode(s)       #bytes to str       bytes.decode(b)

下面是一个udp的例子,其中的 socket.sendall()的输入参数是需要bytes,在python2.x中支持str,所以在我们使用3.x平台时候需要将其转化为bytes,所以上面的转换就可以使用了:

'''Created on 2013-4-6@author: Administrator'''import socket,syshost=sys.argv[1]textport=sys.argv[2]s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)try:    port=int(textport)except ValueError as e:    port=socket.getservbyname(textport,'udp')s.connect((host,port))print("Enter data to transmit:")data=sys.stdin.readline().rstrip()bdata=bytes(data,encoding="utf-8")#str.encode(data)s.sendall(bdata)print("looking for replies;")while 1:    buf=s.recv(2048)    if not len(buf):        break    sys.stdout.write(buf)        

下面是一个不错的博客,有一些python方面的介绍!

http://www.cnblogs.com/rollenholt/category/313456.html

原创粉丝点击