默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 当然你也可以为源码文件指定不同的编码:
# -*- coding: cp-1252 -*-
保留字,我们不能把它们用作任何标识符名称,如import,as,True等,keyword.kwlist查看保留字。
在 Python 3 中,可以用中文作为变量名,非 ASCII 标识符也是允许的了。
1 #!/usr/bin/python3 2 3 # 第一个注释 4 # 第二个注释 5 6 ‘‘‘ 7 第三注释 8 第四注释 9 ‘‘‘ 10 11 """ 12 第五注释 13 第六注释 14 """ 15 print ("Hello, Python!")
正常语句:total = item_one + item_two + item_three
特殊语句:在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\)
例如:total = [‘item_one‘, ‘item_two‘, ‘item_three‘, ‘item_four‘, ‘item_five‘]
Python3 中有六个标准的数据类型:
Python3 的六个标准数据类型中:
1 #!/usr/bin/python3 2 3 print ("我叫 %s 今年 %d 岁!" % (‘小明‘, 10))
后面可以使变量
in | 成员运算符 - 如果字符串中包含给定的字符返回 True | ‘H‘ in a 输出结果 True |
not in | 成员运算符 - 如果字符串中不包含给定的字符返回 True | ‘M‘ not in a 输出结果 True |
r/R | 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 |
print( r‘\n‘ ) print( R‘\n‘ ) |
Python 表达式 | 结果 | 描述 |
---|---|---|
len([1, 2, 3]) | 3 | 长度 |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 组合 |
[‘Hi!‘] * 4 | [‘Hi!‘, ‘Hi!‘, ‘Hi!‘, ‘Hi!‘] | 重复 |
3 in [1, 2, 3] | True | 元素是否存在于列表中 |
for x in [1, 2, 3]: print(x, end=" ") | 1 2 3 | 迭代 |
Python包含以下函数:
序号 | 函数 |
---|---|
1 | len(list) 列表元素个数 |
2 | max(list) 返回列表元素最大值 |
3 | min(list) 返回列表元素最小值 |
4 | list(seq) 将元组转换为列表 |
Python包含以下方法:
序号 | 方法 |
---|---|
1 | list.append(obj) 在列表末尾添加新的对象 |
2 | list.count(obj) 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) 将对象插入列表 |
6 | list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 | list.reverse() 反向列表中元素 |
9 | list.sort( key=None, reverse=False) 对原列表进行排序 |
10 | list.clear() 清空列表 |
11 | list.copy() 复制列表 |
使用tup1 = ()
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合 如将两数组:tup3 = tup1 + tup2
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组。如:deltup
与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。
Python 表达式 | 结果 | 描述 |
---|---|---|
len((1, 2, 3)) | 3 | 计算元素个数 |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 连接 |
(‘Hi!‘,) * 4 | (‘Hi!‘, ‘Hi!‘, ‘Hi!‘, ‘Hi!‘) | 复制 |
3 in (1, 2, 3) | True | 元素是否存在 |
for x in (1, 2, 3): print (x,) | 1 2 3 | 迭代 |
序号 | 方法及描述 | 实例 |
---|---|---|
1 | len(tuple) 计算元组元素个数。 |
>>> tuple1 = (‘Google‘, ‘Runoob‘, ‘Taobao‘) >>> len(tuple1) 3 >>> |
2 | max(tuple) 返回元组中元素最大值。 |
>>> tuple2 = (‘5‘, ‘4‘, ‘8‘) >>> max(tuple2) ‘8‘ >>> |
3 | min(tuple) 返回元组中元素最小值。 |
>>> tuple2 = (‘5‘, ‘4‘, ‘8‘) >>> min(tuple2) ‘4‘ >>> |
4 | tuple(iterable) 将可迭代系列转换为元组。 |
>>> list1= [‘Google‘, ‘Taobao‘, ‘Runoob‘, ‘Baidu‘] >>> tuple1=tuple(list1) >>> tuple1 (‘Google‘, ‘Taobao‘, ‘Runoob‘, ‘Baidu‘) |
注意:键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,且不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
1 #!/usr/bin/python3 2 3 dict = {‘Name‘: ‘Runoob‘, ‘Age‘: 7, ‘Class‘: ‘First‘} 4 5 dict[‘Age‘] = 8 # 更新 Age 6 dict[‘School‘] = "菜鸟教程" # 添加信息 7 8 del dict[‘Name‘] # 删除键 ‘Name‘ 9 dict.clear() # 清空字典 10 del dict # 删除字典
Python字典包含了以下内置函数:
序号 | 函数及描述 | 实例 |
---|---|---|
1 | len(dict) 计算字典元素个数,即键的总数。 |
>>> dict = {‘Name‘: ‘Runoob‘, ‘Age‘: 7, ‘Class‘: ‘First‘} >>> len(dict) 3 |
2 | str(dict) 输出字典,以可打印的字符串表示。 |
>>> dict = {‘Name‘: ‘Runoob‘, ‘Age‘: 7, ‘Class‘: ‘First‘} >>> str(dict) "{‘Name‘: ‘Runoob‘, ‘Class‘: ‘First‘, ‘Age‘: 7}" |
3 | type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 |
>>> dict = {‘Name‘: ‘Runoob‘, ‘Age‘: 7, ‘Class‘: ‘First‘} >>> type(dict) <class ‘dict‘> |
Python字典包含了以下内置方法:
序号 | 函数及描述 |
---|---|
1 | radiansdict.clear() 删除字典内所有元素 |
2 | radiansdict.copy() 返回一个字典的浅复制 |
3 | radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 |
4 | radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值 |
5 | key in dict 如果键在字典dict里返回true,否则返回false |
6 | radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组 |
7 | radiansdict.keys() 返回一个迭代器,可以使用 list() 来转换为列表 |
8 | radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default |
9 | radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 |
10 | radiansdict.values() 返回一个迭代器,可以使用 list() 来转换为列表 |
11 | pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。 |
12 | popitem() 随机返回并删除字典中的最后一对键和值。 |
注意:可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
add() | 为集合添加元素 |
clear() | 移除集合中的所有元素 |
copy() | 拷贝一个集合 |
difference() | 返回多个集合的差集 |
difference_update() | 移除集合中的元素,该元素在指定的集合也存在。 |
discard() | 删除集合中指定的元素 |
intersection() | 返回集合的交集 |
intersection_update() | 返回集合的交集。 |
isdisjoint() | 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 |
issubset() | 判断指定集合是否为该方法参数集合的子集。 |
issuperset() | 判断该方法的参数集合是否为指定集合的子集 |
pop() | 随机移除元素 |
remove() | 移除指定元素 |
symmetric_difference() | 返回两个集合中不重复的元素集合。 |
symmetric_difference_update() | 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。 |
union() | 返回两个集合的并集 |
update() | 给集合添加元素 |
迭代是Python最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器:
1 >>> list=[1,2,3,4] 2 >>> it = iter(list) # 创建迭代器对象 3 >>> print (next(it)) # 输出迭代器的下一个元素 4 1 5 >>> print (next(it)) 6 2 7 >>>
迭代器对象可以使用常规for语句进行遍历:
1 #!/usr/bin/python3 2 3 list=[1,2,3,4] 4 it = iter(list) # 创建迭代器对象 5 for x in it: 6 print (x, end=" ")
while语句:
1 #!/usr/bin/python3 2 3 import sys # 引入 sys 模块 4 5 list=[1,2,3,4] 6 it = iter(list) # 创建迭代器对象 7 8 while True: 9 try: 10 print (next(it)) 11 except StopIteration: 12 sys.exit()
加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数
1 #!/usr/bin/python3 2 3 # 可写函数说明 4 def printinfo( arg1, *vartuple ): 5 "打印任何传入的参数" 6 print ("输出: ") 7 print (arg1) 8 print (vartuple) 9 10 # 调用printinfo 函数 11 printinfo( 70, 60, 50 )
以上实例输出结果:
输出:
70
(60,50)
加了两个星号 ** 的参数会以字典的形式导入。
1 #!/usr/bin/python3 2 3 # 可写函数说明 4 def printinfo( arg1, **vardict ): 5 "打印任何传入的参数" 6 print ("输出: ") 7 print (arg1) 8 print (vardict) 9 10 # 调用printinfo 函数 11 printinfo(1, a=2,b=3)
以上实例输出结果:
输出:
1
{‘a‘: 2, ‘b‘: 3}
python 使用 lambda 来创建匿名函数。
所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数。
如下实例:
1 #!/usr/bin/python3 2 3 # 可写函数说明 4 sum = lambda arg1, arg2: arg1 + arg2 5 6 # 调用sum函数 7 print ("相加后的值为 : ", sum( 10, 20 )) 8 print ("相加后的值为 : ", sum( 20, 20 ))
% 操作符也可以实现字符串格式化。 它将左边的参数作为类似 sprintf() 式的格式化字符串, 而将右边的代入, 然后返回格式化后的字符串. 例如:
1 >>> import math 2 >>> print(‘常量 PI 的值近似为:%5.3f。‘ % math.pi) 3 常量 PI 的值近似为:3.142。
str.format() 的基本使用如下:
1 >>> print(‘{}网址: "{}!"‘.format(‘菜鸟教程‘, ‘www.runoob.com‘)) 2 菜鸟教程网址: "www.runoob.com!"
括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。
在括号中的数字用于指向传入对象在 format() 中的位置,如下所示:
1 >>> print(‘{0} 和 {1}‘.format(‘Google‘, ‘Runoob‘)) 2 Google 和 Runoob 3 >>> print(‘{1} 和 {0}‘.format(‘Google‘, ‘Runoob‘)) 4 Runoob 和 Google
如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数。
1 >>> print(‘{name}网址: {site}‘.format(name=‘菜鸟教程‘, site=‘www.runoob.com‘)) 2 菜鸟教程网址: www.runoob.com
位置及关键字参数可以任意的结合:
1 >>> print(‘站点列表 {0}, {1}, 和 {other}。‘.format(‘Google‘, ‘Runoob‘, other=‘Taobao‘)) 2 站点列表 Google, Runoob, 和 Taobao。
!a (使用 ascii()), !s (使用 str()) 和 !r (使用 repr()) 可以用于在格式化某个值之前对其进行转化:
1 >>> import math 2 >>> print(‘常量 PI 的值近似为: {}。‘.format(math.pi)) 3 常量 PI 的值近似为: 3.141592653589793。 4 >>> print(‘常量 PI 的值近似为: {!r}。‘.format(math.pi)) 5 常量 PI 的值近似为: 3.141592653589793。
可选项 : 和格式标识符可以跟着字段名。 这就允许对值进行更好的格式化。 下面的例子将 Pi 保留到小数点后三位:
1 >>> import math 2 >>> print(‘常量 PI 的值近似为 {0:.3f}。‘.format(math.pi)) 3 常量 PI 的值近似为 3.142。
在 : 后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用。
1 >>> table = {‘Google‘: 1, ‘Runoob‘: 2, ‘Taobao‘: 3} 2 >>> for name, number in table.items(): 3 ... print(‘{0:10} ==> {1:10d}‘.format(name, number)) 4 ... 5 Google ==> 1 6 Runoob ==> 2 7 Taobao ==> 3
如果你有一个很长的格式化字符串, 而你不想将它们分开, 那么在格式化时通过变量名而非位置会是很好的事情。
最简单的就是传入一个字典, 然后使用方括号 [] 来访问键值 :
1 >>> table = {‘Google‘: 1, ‘Runoob‘: 2, ‘Taobao‘: 3} 2 >>> print(‘Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}‘.format(table)) 3 Runoob: 2; Google: 1; Taobao: 3
也可以通过在 table 变量前使用 ** 来实现相同的功能:
1 >>> table = {‘Google‘: 1, ‘Runoob‘: 2, ‘Taobao‘: 3} 2 >>> print(‘Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}‘.format(**table)) 3 Runoob: 2; Google: 1; Taobao: 3
注意:因为 str.format() 是比较新的函数, 大多数的 Python 代码仍然使用 % 操作符。但是因为这种旧式的格式化最终会从该语言中移除, 应该更多的使用 str.format().
https://www.runoob.com/python3/python3-file-methods.html
.................
原文:https://www.cnblogs.com/zzhoo/p/12735313.html