py2-3

来源:互联网 发布:mysql 多个字段排序 编辑:程序博客网 时间:2024/06/03 21:51

input

  • raw_input()

在py2版本中,raw_input接收输入流并直接转换存储为string类型

  • input()

py2版本中,通过根据输入类型不同存储为不同格式。

比如像输入string,需在内容外包裹单引或者双引

py3整合input与raw_input,将所有输入作为string保存

print

py2中print不是将print作为一个方法函数,二十当做语句使用,调用时不能再后面直接()

Ps:同样的还有exec语句转换成了exec()

str=

repr

Python 有办法将任意值转为字符串:将它传入repr() 或str() 函数。

函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话,str() 会返回与repr()等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。字符串和浮点数,有着独特的解读方式。


str直接将object转换成string

repr则更类似于Java中的toString(),将相关类型内容显示

unicode与str

unicode、utf-8、ascii编码等相关前置知识可以浏览TYuenCN博客

ANSI是默认的编码方式。对于英文文件是ASCII编码,对于简体中文文件是GB2312编码(只针对Windows简体中文版,如果是繁体中文版会采用Big5码)

str和unicode都是basestring的子类,而实际上,str是字节串,由unicode经过编码(encode)后的字节组成。unicode才是真正意义上的字符串,由字符组成

下面是一个基本的转换流程

str -> decode('the_coding_of_str') -> unicode

unicode -> encode(‘the_coding_you_want‘) -> str

decode

The method decode() decodes the string using the codec registered for encoding. It defaults to the default string encoding.

#!/usr/bin/pythonStr = "this is string example....wow!!!";Str = Str.encode('base64','strict');print "Encoded String: " + Strprint "Decoded String: " + Str.decode('base64','strict')Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=Decoded String: this is string example....wow!!!

encode

The method encode() returns an encoded version of the string. Default encoding is the current default string encoding. The errors may be given to set a different error handling scheme.

#!/usr/bin/pythonstr = "this is string example....wow!!!";print "Encoded String: " + str.encode('base64','strict')Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
0 0