设为首页 加入收藏

TOP

python基础篇----字符串unicode
2017-10-01 13:36:11 】 浏览:4086
Tags:python 基础 ---- 字符串 unicode

python中处理中文常要用到unicode,因为较容易遇到字符串编码的问题,我一般都是将字符串统一转成unicode去处理

 

python中定义一个unicode字符串,可以在字符串前面加u:

str=u"hello world"

 

python中定义不转义的字符串,可以在字符串前面加r:

path=r"c:\programfile\test"

 

解码将其他字符串格式转为unicode:

ret=str.decode("gb2312")
ret=str.decode("ascii")
ret=str.decode("utf-8")

 

编码将unicode字符转为其他字符串格式:

ret=str.encode(“gb2312”)
ret=str.encode("ascii")
ret=str.encode("utf-8")

 

chardet判断字符串为何种编码格式:

encode = chardef.detect(str)
print encode['encoding']

 

字符串格式化%s

print "test for %s, value is %d"%("format", 123)

 

一般在py文件开始的时候都加上#encoding=utf-8,避免文件中有中文乱码


处理字符串问题最主要是知道字符串输入的时候是什么格式,在输入的时候处理好字符串,处理过程就好办了

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python基础(二),Day2 下一篇Python开发【第一篇】:初识Python

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目