练习1.1:打印ASCII编码表,包括可见和不可见字符
#coding=utf-8
asciilist = []
chrlist = []
for i in range(255):
asciilist.append(i)
#a.append(i)为NoneType,返回值为None,布尔判断为false 不能写成a=a.append(i)
print asciilist
for i in asciilist:
chrlist.append(chr(i))
print chrlist
a 97, z 122, A 65, Z 90, 0 48, 9 57
a-z: 97-122
A-Z: 65-90
0-9: 48-57
练习1.2:打印大写、小写、0-9数字
分析:拼接字符串,在知道ascii的范围的基础上
upper_letters='' #拼接字符串
for i in range(65,91):
upper_letters=upper_letters+chr(i)
for i in range(97,123):
upper_letters=upper_letters+chr(i)
for i in range(48,58):
upper_letters=upper_letters+chr(i)
print upper_letters
练习1.3:26个字母大小写成对打印
#coding=utf-8
#大小写成对出现,并拼接在一个字符串
letters=''
for i in range(26):
print chr(65+i), chr(65+i+32)
letters = letters +chr(65+i)+chr(65+i+32)
print letters
练习1.4:输入加解密
#encoding=utf-8
#加解密 规则:a->e b->f c->g w->a x->b y->c z->d
def encode(string):
str_encode = ""
for i in string:
if isinstance(i,str):
if i>='a' and i<='v':
str_encode += chr(ord(i)+4)
elif i>'v' and i<='z':
str_encode += chr(ord(i)-26+4)
return str_encode
def decode():
str_encode = encode(str_original)
str_decode = ""
for i in str_encode:
if isinstance(i,str):
if i>='e' and i<='z':
str_decode += chr(ord(i)-4)
elif i>='a' and i<='d':
str_decode += chr(ord(i)+26-4)
return str_decode
str_original = "abcdwxyz"
print "str_original=",str_original
print "str_encode=",encode(str_original)
print "str_decode=",decode()
练习5:字符的编解码练习
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
print type(u'我')
print type(u"我".encode('utf-8'))
print type(u"我".decode('utf-8'))
print "我".encode('utf-8').decode('utf-8')
print "我".encode('utf-8').decode('utf-8')
# python默认编码是ascii,设定为utf-8,这里“我”是字节字符型,python自动decode为unicode,然后encode成utf-8,再decode成字节字符型
if isinstance(s, basestring): #判断是否是字符串
print u”是字符串”