[转]python str与bytes之间的转换

原文:http://www.cnblogs.com/zqifa/p/python-7.html

# bytes object
b = b"example"

# str object
s = "example"

# str to bytes
sb = bytes(s, encoding = "utf8")

# bytes to str
bs = str(b, encoding = "utf8")

# an alternative method
# str to bytes
sb2 = str.encode(s)

# bytes to str
bs2 = bytes.decode(b)
时间: 2024-08-02 15:13:11

[转]python str与bytes之间的转换的相关文章

python str与bytes之间的转换

1 # bytes object 2 b = b"example" 3 4 # str object 5 s = "example" 6 7 # str to bytes 8 bytes(s, encoding = "utf8") 9 10 # bytes to str 11 str(b, encoding = "utf-8") 12 13 # an alternative method 14 # str to bytes 1

python timestamp和datetime之间的转换

做开发中难免时间类型之间的转换, 最近就发现前端js和后端django经常要用到这个转换, 其中jsDate.now()精确到毫秒,而Python中Datetime.datetime.now()是精确到微秒的. 1. 字符串日期时间转换成时间戳 # '2015-08-28 16:43:37.283' --> 1440751417.283 # 或者 '2015-08-28 16:43:37' --> 1440751417.0 def string2timestamp(strValue): try

Python datetime与timestamp之间的转换

在用Python处理datetime和timestamp的转换时发现在时区方面,Python的处理是个大坑. 因为Python的time是默认localtime输入来处理的,导致脚本在本地运行和在服务器运行会得到不一样的结果.一不注意就会中招. R中也会碰到时区的问题,但是R的方法提供了tz选项来指定日期的时区,简化了问题.而Python 中的time.mktime无法对时区进行指定,带来了很多麻烦.查了很久,发现有一个time.timezone的属性,可以根据运行脚本的机器的时间,来灵活处理时

python——时间与时间戳之间的转换

1.将时间转换成时间戳 将如上的时间2017-09-16 11:28:54转换成时间戳 利用strptime()函数将时间转换成时间数组 利用mktime()函数将时间数组转换成时间戳 #!/usr/bin/env python # -*- coding:utf-8 -*- import time dtime= "2017-09-16 11:28:54" #转换成时间数组 timeArray = time.strptime( dtime, "%Y-%m-%d %H:%M:%S

python时间和时间戳之间的转换

(1)例如格式2012-07-31 00:01:18,根据该时间计算时间戳: 将"2012-03-28 06:53:40"转化为时间戳 s = time.mktime(time.strptime('2012-03-28 06:53:40', '%Y-%m-%d %H:%M:%S')) (2)根据时间戳得到如2012-07-31 00:01:18的时间格式,显示的时间形式可以根据format指定的 import time timestamp = time.strftime('%Y-%m-

python 日期和时间之间的转换整理

1.获取当前时间戳 time.time() 2.获取当前时间 time.localtime() 3.获取格式化的日期时间 time.strftime(format,t) 4.将"%a %b %d %H:%M:%S %Y"(如:"Sat Mar 28 22:24:24 2016")格式化日期时间转换为时间戳 time.mktime(time.strptime(t,format)) 原文地址:https://www.cnblogs.com/lhj818/p/116706

python string类型 bytes类型 bytearray类型

一.python3对文本和二进制数据做了区分.文本是Unicode编码,str类型,用于显示.二进制类型是bytes类型,用于存储和传输.bytes是byte的序列,而str是unicode的序列. str类型: 1 >>> s = u'你好' 2 >>> s 3 '你好' 4 >>> type(s) 5 <class 'str'> bytes类型: 1 >>> b = b'abc' 2 >>> b 3

Python 3中bytes和str的分别

最近把一段py2的代码转换到py3的代码,结果运行到向socket中写数据的代码部分出现了'str' does not support the buffer interface这样一个错误. 一番搜索之后,发现py3里是严格区分了str和bytes的.怎么理解str和bytes呢?你可以认为str是一段文本,比如“abcd#%$^*&”什么的,而bytes呢,是二进制的一堆0,1的比特而已.看下面的图: 可以看到str的类型是class 'str',而str.encode()以后类型是class

[Python爬虫] 中文编码问题:raw_input输入、文件读取、变量比较等str、unicode、utf-8转换问题

最近研究搜索引擎.知识图谱和Python爬虫比较多,中文乱码问题再次浮现于眼前.虽然市面上讲述中文编码问题的文章数不胜数,同时以前我也讲述过PHP处理数据库服务器中文乱码问题,但是此处还是准备简单做下笔记.方便以后查阅和大家学习. 中文编码问题的处理核心都是--保证所有的编码方式一致即可,包括编译器.数据库.浏览器编码方式等,而Python通常的处理流程是将unicode作为中间转换码进行过渡.先将待处理字符串用unicode函数以正确的编码转换为Unicode码,在程序中统一用Unicode字