1.字符串

字符串基本有两种类型,str和bytes

>>> s="a"

>>> type(s)

<class 'str'>                    #字符串 -- > Unicode(日常编程中的内容使用的是这个)

>>> s="中国"

>>> s.encode("utf-8")

b'\xe4\xb8\xad\xe5\x9b\xbd'     #b代表类型是bytes

>>> type(s.encode("utf-8"))

<class 'bytes'>                 #str encode后是bytes类型(会用在网络传输上)

>>> s.encode("utf-8").decode("utf-8")

'中国'

>>> type(s.encode("utf-8").decode

("utf-8"))                      #bytes decode后是str

<class 'str'>

注意:编码方式与解码方式前后应该保持一致,否则在需要编解码的内容为非英文时,会因为字符集对应不上,报错。

>>> s="a"                     #s是英文

>>> s.encode("utf-8")

b'a'

>>> s.encode()                #encode()中不写编码方式,默认是utf-8

b'a'

>>> s.encode("gbk")           #由于s是英文,所以gbk编码与utf-8编码的输出一样

b'a'

>>> s.encode("gbk").decode("utf-8")           #编码方式gbk,解码方式utf-8,不会报错

'a'

>>> s="中"                    #s是中文

>>> s.encode()                #encode()中不写编码方式,默认是utf-8

b'\xe4\xb8\xad'

>>> s.encode("utf-8")

b'\xe4\xb8\xad'                #与不写编码方式的结果输出一致

>>> s.encode("gbk")

b'\xd6\xd0'                    #由于s是中文,所以utf-8与gbk编码方式的输出不一致

>>> s.encode("gbk")

b'\xd6\xd0'

>>> s.encode("gbk").decode("utf-8")           #编码方式gbk,解码方式utf-8,会报错

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byte

utf-8不能解码,

2.random(随机):获得随机的东西。

1)    引入random包

>>> import random

2)    查看random

>>> dir(random)

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

>>> dir()

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'random']

#dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表

3)    random.random()          #随机生成0-1之间的小数,[0,1)

>>> random.random()

0.3169229105176976

>>> random.random()

0.0717880522606662

>>> help(random.random)

random(...) method of random.Random instance

random() -> x in the interval [0, 1).

4)    random.randint(a,b)           #随机生成范围内的整数[a,b]

>>> random.randint(1,1000)

902

>>> random.randint(1,1000)

62

>>> help(random.randint)

randint(a, b) method of random.Random instance

Return random integer in range [a, b], including both end points.

5)    random.choice(列表名)       #随机取出列表中的某一元素

>>> s=[1,1.2,"早上好",{1:2}]

>>> random.choice(s)

{1: 2}

>>> random.choice(s)

'早上好'

6)    random.shuffle(列表名)       #打乱列表参数顺序

>>> s

[1, 1.2, '早上好', {1: 2}]               #s列表当前的顺序

>>> random.shuffle(s)

>>> s                              #并未直接返回值,需要输入s再次查看

[1, '早上好', {1: 2}, 1.2]

>>> random.shuffle(s)                #再次洗牌

>>> s

[1.2, {1: 2}, 1, '早上好']

7) random.uniform(a,b)           #在a,b范围内随机生成一个小数

>>> random.uniform(7,80)

58.444125752076054

>>> random.uniform(7,80)

72.05529541894796

3.ord()                            #返回字符对应的ASCII值或unicode数值

>>> ord("严")

20005                             #汉字“严”的unicode编码是20005

4.chr()                           #整数作参数,返回一个对应的字符。

>>> chr(20005)

'严'

5.string

1)    引入string包

>>> import string

2)    查看string

>>> dir(string)

['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

3)    string.ascii_letters              #查看所有大小写字母

>>> string.ascii_letters

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

4)    string.ascii_lowercase          #查看所有小写字母

>>> string.ascii_lowercase

'abcdefghijklmnopqrstuvwxyz'

5)    string.ascii_uppercase          #查看所有大写字母

>>> string.ascii_uppercase

'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

6.字串转换为列表list

>>> list(string.ascii_letters)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

7.切片                            #列表中取几个元素

>>> a=list(string.ascii_letters)

>>> a

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

>>> a[:10]                          #只取列表a前10个元素

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

8.join                                        #将列表转换为一个字符串

>>> "".join(a[:10])                             #空字符串与列表元素组合

'abcdefghij'

注意:

一个字符串转换为列表可以使用list,但是列表转换成字符串不能使用str

>>> a="alkjdhfgkadg"

>>> list(a)

['a', 'l', 'k', 'j', 'd', 'h', 'f', 'g', 'k', 'a', 'd', 'g']

>>> s=['a', 'l', 'k', 'j', 'd', 'h', 'f', 'g', 'k', 'a', 'd', 'g']

>>> str(s)

"['a', 'l', 'k', 'j', 'd', 'h', 'f', 'g', 'k', 'a', 'd', 'g']"            #仅仅是在列表外加了“”

9.代码过长换行

1)    回车

>>> a=(1,3,

... 4,5

... ,7,9)

>>> a

(1, 3, 4, 5, 7, 9)

2)    \

>>> a=(1,2,\

...  3,4)

>>> a

(1, 2, 3, 4)

>>> a=10

>>> if a==\

... 10\

... :

...     print(True)

...

True

小练习:

声明一个中文的字符串,查看一下类型,然后转换为bytes类型,在type一下,然后bytes类型转换为str类型

>>> s="早上好"
>>> type(s)
<class 'str'>
>>> s.encode("gbk")
b'\xd4\xe7\xc9\xcf\xba\xc3'
>>> type(s.encode("gbk"))
<class 'bytes'>
>>> b'\xd4\xe7\xc9\xcf\xba\xc3'.decode('gbk')
'早上好'

# b'\xd4\xe7\xc9\xcf\xba\xc3'可以直接接decode,不用加括号

小练习:

随机生成100-·101之间的数字

>>> 100+random.random()

100.44705467177177

>>> 100+random.random()

100.76812721548731

小练习:

随机生成一个小写字母

>>> ord("a")

97

>>> chr(97+random.randint(1,25))

'g'

>>> chr(97+random.randint(1,25))

'y'

小练习:

随机生成一个大写字母

>>> ord("A")

65

>>> chr(65+random.randint(1,25))

'Q'

>>> chr(65+random.randint(1,25))

'F'

>>> chr(ord("A")+random.randint(1,25))

'J'                                              #不查ASCII表实现的方法

小练习:

随机生成10个小写字母

>>> result=""

>>> for i in range(10):                                #循环

...     result+=chr(ord("a")+random.randint(0,25))       #拼字符串与随机生成小写字母

...

>>> print(result)

lnqzhedffg

小练习:

随机生成10个大写字母

>>> result=""

>>> for i in range(10):

...     result+=chr(ord("A")+random.randint(0,25))

...

>>> print(result)

GYZDQUFHZL

小练习:

随机生成5个小写字母,5个大写字母

>>> result=""

>>> for i in range(10):

...     if i<=5:         # i的取值是0,1,2,3,4,5,共6个

...         result+=chr(ord("a")+random.randint(0,25))

...     else:

...         result+=chr(ord("A")+random.randint(0,25))

...

>>> print(result)

duzceiKLLB            #输出的结果为6+4,错误。注意range是从0开始的!!

更改后的程序是:

>>> result=""

>>> for i in range(10):

...     if i<5:

...         result+=chr(ord("a")+random.randint(0,25))

...     else:

...         result+=chr(ord("A")+random.randint(0,25))

...

>>> print(result)

tzkyhWXKTB

随机生成不限定固定大小个数的10个字母

>>> result=""

>>> import random

>>> result=""

>>> lower_case_letter_num=random.randint(1,10)

>>> upper_case_letter_num=10-random.randint(1,10)

>>> for i in range(10):

...     if i < lower_case_letter_num:

...         result+=chr(ord("a")+random.randint(0,25))

...     else:

...         result+=chr(ord("A")+random.randint(0,25))

...

>>> print(result)

ujvdhdwpoM

#注意:该解法是在一开始就限定了小写字母几个,大写字母几个,而不是随着计算的过程,,,慢慢进行分配

小练习:

随机生成10个包含大小写字母混拼的字符串

方法一:

1)    生成全部的大小写字母

>>> a=string.ascii_letters

>>> a

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

2)    将字符串转换为list

>>> s=list(a)

>>> s

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

3)    将list洗牌

>>> random.shuffle(s)

>>> s

['H', 'j', 'z', 'L', 'p', 'i', 'O', 'C', 'q', 'y', 'u', 'd', 'c', 'Z', 'w', 'm', 'F', 'P', 's', 't', 'Q', 'a', 'S', 'g', 'h', 'G', 'f', 'U', 'n', 'V', 'Y', 'J', 'R', 'K', 'o', 'k', 'b', 'N', 'v', 'I', 'M', 'e', 'A', 'r', 'W', 'X', 'E', 'D', 'l', 'B', 'T', 'x']

注意: random.shuffle(s)执行后,需要查看s的变化,而不能将random.shuffle赋值给j.执行完成后查看j的输出,否则无所出

>>> j=random.shuffle(s)

>>> j

>>>

4)    切片,取出洗牌后的10个元素

>>> h=s[:10]

>>> h

['j', 'o', 'I', 'm', 'p', 'Z', 'O', 'B', 'G', 's']

5)    将列表转换成字符串,输出最终结果

>>> "".join(h)

'joImpZOBGs'

最终的程序就是:

>>> import random

>>> import string

>>> a=list(string.ascii_letters)

>>> random.shuffle(a)

>>> "".join(a[:10])

'CwWPqEuvgy'

注意:random.shuffle()括号中必须是一个list的变量名,而不能直接写运算后是list的过程。random.shuffle()的使用方法是,将一个list存到变量里,在传到shuffle里才能用。

方法二:

1)    生成全部的大小写字母

>>> a=string.ascii_letters

>>> a

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

2)    将字符串转换为list

>>> s=list(a)

>>> s

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

3)    随机取出10个元素

>>> for i in range(10):

...     random.choice(s)

...

'D'

'z'

'l'

'c'

'A'

'O'

'R'

'j'

'v'

'w'

>>>

4)    将10个元素转换为str

>>> "".join(random.choice(s) for i in range(10))

'TMlaOCofkd'

最终的程序就是:

>>> import random

>>> import string

>>> "".join(random.choice(list(string.ascii_letters)) for i in range(10))

'fAMsFctpKq'

小知识:

1.bytes类型都是gbk?

no!gbk与utf-8是编码集,bytes类型是经过编码产生的。但是编码方式有好几种:utf-8,iso,8259,拉丁1等。

2.>>> type(早上好.encode("gbk").decode("gbk"))

<class 'str'>

注意,此处的早上好是一个变量名字,并不是一个字符串,如果是一个字符串,会提示报错(not defined),不会输出结果

>>> 早上好="早上好"

3.python 2与python 3的区别

1)    python2的默认字符串类型也是str,但是是bytes类型

所以,str经过decode是unicode

python3的默认字符串类型也是str,但是是unicode类型

所以,str经过encode是bytes类型

2)    python2默认使用gbk编码,所以解码时也是要gbk

python3默认使用utf-8编码,所以解码时要用utf-8

总结:

encode: 都是用来得到非unicode类型字符串

decode:都是用来得到unicode类型

4.gbk,utf-8,unicode之间的差别

Unicode编码(str类型):包含了全世界所有字符。但是只是用来在内存中使用。一旦需要存储到文件,或者需要在网络中传输,需要转换成bytes, 服务器之间传递的数字,必须是bytes.API的调用也必须是bytes

默认计算机系统不支持unicode。

查看网页的编码方式:

网页源码 -- > charset -- >设定字符集

打开某个网页->右键->查看网页源代码Ctrl+U->必有“<meta charset="utf-8">”字样。

基本中国的网站,编码方式是gbk或utf-8,但是绝对没有unicode

bytes类型:存储到文件(硬盘)或是网络传输

不同国家使用的编码不同,中国使用gbk,欧洲使用iso8859,台湾使用big5(繁体)

没有全世界统一使用的编码

所以,编码方式选择gbk,utf-8还是其他的编码方式呢?

取决于你的应用程序是针对所有的处理都是utf-8,那么数据就要是utf-8.使用utf-8编码。

通过gbk或utf-8编码的bytes类型字符串,就是为了能够存储与传输。

最新文章

  1. 一张图告诉你,只会Node.JS还不够!
  2. Vue.js说说组件
  3. NPOI读取Excel帮助类,支持xls与xlsx,实现公式解析,空行的处理
  4. 转:Java中abstract和interface的区别
  5. 【亚瑟士 ASICS 系列】
  6. Android中log使用方法
  7. centos7 firewall 防火墙 命令
  8. 去除DedeCms 5.7后台版权广告链接的方法
  9. JavaScript对象就是一组属性(方法)的集合
  10. c# 图片路径转byte[] 插到数据库BLOB 图片长宽自定义
  11. 代理模式(proxy)
  12. lighttpd为什么要accept多次呢
  13. HTML5 SSE自动推送
  14. 关于nginx架构探究(2)
  15. N bulbs(规律)
  16. Faster R-CNN
  17. 项目Alpha冲刺(团队)-第一天冲刺
  18. Centos7上使用tomcat8
  19. C#、Java中的一些小知识点总结(持续更新......)
  20. 页面注册系统--使用forms表单结合ajax

热门文章

  1. 本地Debug Asp.net MVC 无法加载css与js
  2. python中sys和os模块的使用
  3. Linux服务安装配置总结
  4. /etc/hosts和/etc/hostname区别
  5. .Net MVC TextBoxFor 扩展 placeholder 与 class 属性
  6. Beautiful Soup库基础用法(爬虫)
  7. Android之ListView动态添加数据(SQLiteOpenHelper类添加数据)
  8. Pycharm初始创建项目和环境搭建
  9. 涂抹mysql笔记-InnoDB/MyISAM及其它各种存储引擎
  10. psi