python编码

关于python编码

Python2的默认编码是ASCII,不能识别中文字符,需要显式指定字符编码;Python3的默认编码为Unicode,可以识别中文字符。

一个字符不等价于一个字节,字符是人类能够识别的符号,而这些符号要保存到计算的存储中就需要用计算机能够识别的字节来表示。一个字符往往有多种表示方法,不同的表示方法会使用不同的字节数。这里所说的不同的表示方法就是指字符编码,比如字母A-Z都可以用ASCII码表示(占用一个字节),也可以用UNICODE表示(占两个字节),还可以用UTF-8表示(占用一个字节)。字符编码的作用就是将人类可识别的字符转换为机器可识别的字节码,以及反向过程。UNICDOE才是真正的字符串,而用ASCII、UTF-8、GBK等字符编码表示的是字节串。关于这点,我们可以在Python的官方文档中经常可以看到这样的描述"Unicode string" , " translating a Unicode string into a sequence of bytes"。

我们写代码是写在文件中的,而字符是以字节形式保存在文件中的,因此当我们在文件中定义字符串时被当做字节串也是可以理解的。但是,我们需要的是字符串,而不是字节串。

>>> # Python2
>>> a = 'Hello,中国'  # 字节串,长度为字节个数 = len('Hello,')+len('中国') = 6+2*2 = 10
>>> b = u'Hello,中国'  # 字符串,长度为字符个数 = len('Hello,')+len('中国') = 6+2 = 8

python2和python3使用的默认编码

>>> # Python2
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
 
>>> # Python3
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'

python转码过程

encode()方法以encoding指定的编码格式对字符串进行编码。将Unicode字符串(中的代码点)转换特定字符编码对应的字节串的过程和规则。
decode()方法以encoding指定的编码格式对字符串进行解码。将特定字符编码的字节串转换为对应的Unicode字符串(中的代码点)的过程和规则。
原有编码         -->      unicode编码      -->      目的编码
decode解码    -->       unicode编码      -->      encode编码
python2:字节串-->decode('原来的字符编码')-->Unicode字符串-->encode('新的字符编码')-->字节串
#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
utf_8_a = '我爱中国'
gbk_a = utf_8_a.decode('utf-8').encode('gbk')
print(gbk_a.decode('gbk'))
 
输出结果:
我爱中国

python3:字符串-->encode('新的字符编码')-->字节串

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
utf_8_a = '我爱中国'
gbk_a = utf_8_a.encode('gbk')
print(gbk_a.decode('gbk'))
 
输出结果:
我爱中国

程序练习

demo1.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time  : 2018-4-10 20:35
# @Author: yangjian
# @File  : demo1.py
'''
输入一串字符,判断数字、字母、空格、其他字符各有多少个
'''


while 1:
    strings = input("Please input a string(quit will be exit):")
    alpha, digit, space, other = 0, 0, 0, 0
    if strings.strip() == "quit":
       exit(1)
    for i in strings:
        if i.isdigit():
            digit += 1
        elif i.isspace():
            space += 1
        elif i.isalpha():
            alpha += 1
        else:
            other += 1
    print("alpha = {0}".format(alpha))
    print("digit = {0}".format(digit))
    print("space = {0}".format(space))
    print("other = {0}".format(other))

demo2.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time  : 2018-4-10 20:50
# @Author: yangjian
# @File  : demo2.py

'''
ABCD乘以9=DCBA,求A、B、C、D的值分别是
一个四位数乘以9等于一个四位数,那么A一定是1,那么D一定是9咯
# for A in [1]: 为什么可以写成这样呢,应为range()返回的就是一个列表
'''

for A in range(1,10):
    for B in range(0,10):
        for C in range(0,10):
            for D in range(1,10):
                if (1000*A + 100*B + 10*C + D)*9 == (1000*D + 100*C + 10*B + A):
                    print("A = {0}".format(A))
                    print("B = {0}".format(B))
                    print("C = {0}".format(C))
                    print("D = {0}".format(D))
                    print("{0}{1}{2}{3}x9={4}{5}{6}{7}".format(A, B, C, D, D, C, B, A))

demo3.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time  : 2018-4-10 21:07
# @Author: yangjian
# @File  : demo3.py
'''
九宫格
                -----------
                |A | B | C|
                |D | E | F|
                |G | H | I|
                -----------
所有的横竖斜线加起来都等于15
A:1-9
B:1-9 除去 A
C: 1-9 除去 A和B
'''
number = list()
for i in range(1,10):
    number.append(i)
print(number)
count = 0
for A in number:
    #for B in [i for i in range(1,10) if i != A]: # 这种写法更简洁
    a = list()
    a = number.copy()
    a.remove(A)
    for B in a:
        b = list()
        b = a.copy()
        b.remove(B)
        for C in b:
            c = list()
            c = b.copy()
            c.remove(C)
            for D in c:
                d = list()
                d = c.copy()
                d.remove(D)
                for E in d:
                    e = list()
                    e = d.copy()
                    e.remove(E)
                    for F in e:
                        f = list()
                        f = e.copy()
                        f.remove(F)
                        for G in f:
                            g = list()
                            g = f.copy()
                            g.remove(G)
                            for H in g:
                                h = list()
                                h = g.copy()
                                h.remove(H)
                                for I in h:
                                    if (A + B + C == D + E + F == G + H + I == A + D + G == B + E + H == C + F + I == A + E + I == I + E + A == C + E + G == 15):
                                        print(
                                            '''
                                            第{9}种例子
                                            -----------------
                                            |{0} | {1} | {2}|
                                            |{3} | {4} | {5}|
                                            |{6} | {7} | {8}|
                                            -----------------
                                            '''.format(A, B, C, D, E, F, G, H, I, count)
                                        )
                                        count += 1

demo4.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time  : 2018-4-10 21:59
# @Author: yangjian
# @File  : demo4.py

'''
求阶乘的和
0! + 1! + 2! + 3! + 4! + 5! + n!
把需要重复用到的部分写成函数,后面进行调用。

'''
def jc(n):
    result = 1
    if n == 0:
        return result
    else:
        for i in range(1, n+1):
            result *= i
        return result
# print(jc(0))
# print(jc(2))
# print(jc(3))
# print(jc(4))
# print(jc(5))
n = input("Please input number n:")
count = 0
for i in range(0,int(n)+1):
    count += jc(i)
print("count = {0}".format(count))
原文地址:https://www.cnblogs.com/yangjian319/p/8798546.html