支持中文的编码有: utf-8,gbk,gb2312, 在其他应用中很多默认是用 utf-8 的格式, 而在 Windows 的 cmd 中输出中文需要使用 gbk 格式
Python2.X 中默认的编码格式是 ASCII 格式, 在没修改编码格式时无法正确打印汉字, 所以在读取中文时会报错, 解决方法只要在文件开头加入 # -*- coding: UTF-8 -*- 或者 #coding=utf-8 就行了
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- print "你好, 世界";
Python2.X 中如果要想让 Windows 下 cmd 显示中文, 需要将编码格式改为 gbk, 或者在代码中加入如下:
- import sys
- reload(sys)
- print(sys.getdefaultencoding())
- sys.setdefaultencoding("utf -8")
- print(sys.getdefaultencoding())
注意: Python3.X 源码文件默认使用 utf-8 编码, 所以可以正常解析中文, 无需指定 UTF-8 编码.
还有一种格式是可以用转换来完成的: 原有编码 --> unicode 编码 --> 目的编码, 指的是在字符串前面加上 u, 表示是以 Unicode 编码格式存储, 当打印的时候它会根据客户端需要的编码格式自动转换为所需的编码, 如下:
- m = u"哈哈哈"
- print(m)
或者可以在打印输出的时候做解码和编码操作, 指的是先用 decode 转换成 Unicode 格式, 再用 encode 转换成所需的编码格式, 如下:
- n = "你好"
- print(n.decode("utf-8").encode("gbk"))
decode("utf-8") 解码 -> unicode -> encode("gbk")
二, 练习题
1), 判断一个字符串数字有多少个, 字符有多少个, 空格有多少个, 其他字符有多少个
- while 1:
- strings = input("Please input a string(input quit is exit):")
- dig, alpha, space, other = 0, 0, 0, 0
- if strings.strip() == "quit":
- exit()
- else:
- for i in strings:
- if i.isdigit():
- dig += 1
- elif i.isalpha():
- alpha += 1
- elif i.isspace():
- space += 1
- else:
- other += 1
- print("dig = {0},alpha = {1},space = {2},other = {3}".format(dig, alpha, space, other))
2),ABCD 乘以 9=DCBA, 求 ABCD 各为多少
- for a in [1]:
- for b in range(0, 10):
- for c in range(0, 10):
- for d in [9]:
- if (a*1000+b*100+c*10+d)*9 == d*1000+c*100+b*10+a:
- print("a={0},b={1},c={2},d={3}".format(a, b, c, d))
3), 九宫格
-------------
| A | B | C |
| D | E | F |
| G | H | I |
-------------
所有横竖斜线加起来都等于 15
- number = list()
- for i in range(1, 10):
- number.append(i)
- for A in number:
- a = number.copy()
- a.remove(A)
- for B in a:
- b = a.copy()
- b.remove(B)
- for C in b:
- c = b.copy()
- c.remove(C)
- for D in c:
- d = c.copy()
- d.remove(D)
- for E in d:
- e = d.copy()
- e.remove(E)
- for F in e:
- f = e.copy()
- f.remove(F)
- for G in f:
- g = f.copy()
- g.remove(G)
- for H in g:
- 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 == C + E + G== 15):
- print("""
- -------------
- | {0} | {1} | {2} |
- | {3} | {4} | {5} |
- | {6} | {7} | {8} |
- -------------""".format(A, B, C, D, E, F, G, H, I))
4), 阶乘
0!+ 1!+ 2!+ 3!+...+ n!
- def jc(n):
- result = 1
- if n == 0:
- return result
- else:
- for i in range(1, n + 1):
- result *= i
- return result
- n = input("Pls input num:")
- count = 0
- for i in range(0, int(n) + 1):
- count += jc(i)
- print("count={0}".format(count))
编码格式
来源: http://www.bubuko.com/infodetail-2558742.html