python编程语言简明教程,翻译自以下仓库:
Python-Lectures
原仓库是一系列的jupyter notebook,可以直接在jupyter环境下运行程序示例。我添加了中文注释,并改为了兼容python3
字符串Strings
字符串表示一段文字,用配对的单引号或双引号表示。
String0 = 'Taj Mahal is beautiful'
String1 = "Taj Mahal is beautiful"
String2 = '''Taj Mahal
is
beautiful'''
print(String0 , type(String0))
print(String1, type(String1))
print(String2, type(String2))
Taj Mahal is beautiful <class ‘str’>
Taj Mahal is beautiful <class ‘str’>
Taj Mahal
is
beautiful <class ‘str’>
字符串的序号索引和切片索引与列表类似:
print(String0[4])
print(String0[4:])
M
Mahal is beautiful
字符串的内置函数
find( ) 返回指定元素的序号索引。 如果没找到返回 -1.
print(String0.find('al'))
print(String0.find('am'))
7
-1
注意,此处7返回的是要查找的’al’的第一个字符a的序号.
print(String0[7])
a
find( ) 还可以在指定的序号范围内查找:
print(String0.find('j',1))
print(String0.find('j',1,3))
2
2
capitalize( ) 将首字母大写:
String3 = 'observe the first letter in this sentence.'
print(String3.capitalize())
Observe the first letter in this sentence.
center( ) 根据指定的宽度将字符串内容居中排列:
String0.center(70)
' Taj Mahal is beautiful '
也可以指定填充左右空白的符号:
String0.center(70,'-')
‘------------------------Taj Mahal is beautiful------------------------’
zfill( ) 用0来填补前面的空白.
String0.zfill(30)
‘00000000Taj Mahal is beautiful’
expandtabs( ) 可以改变制表符的占位宽度. 制表符’\t’ 默认宽度为8.
s = 'h\te\tl\tl\to'
print(s)
print(s.expandtabs(1))
print(s.expandtabs())
h e l l o
h e l l o
h e l l o
index( ) 用法与 find( ) 类似,唯一的区别是,find找不到元素的时候返回-1,而index找不到元素的时候会报错。
print(String0.index('Taj'))
print(String0.index('Mahal',0))
print(String0.index('Mahal',10,20))
0
4
--------------------------------------------------------------------------- ValueError Traceback (most recent call
last) in
1 print(String0.index(‘Taj’))
2 print(String0.index(‘Mahal’,0))
----> 3 print(String0.index(‘Mahal’,10,20))ValueError: substring not found
endswith( ) 判断一个字符串是否以指定的字符结尾:
String0.endswith('y')
False
判断的范围也可以指定:
print(String0.endswith('l',0))
print(String0.endswith('M',0,5))
True
True
count( ) 统计特定元素在字符串中出现的次数,范围也可指定
print(String0.count('a',0))
print(String0.count('a',5,10))
4
2
join( ) 在每一个字符之间插入指定字符:
'a'.join('*_-')
‘*a_a-’
‘*_-’ 中每个符号间都插入了一个字符 ‘a’
因此 join( ) 可以用来把一个列表转化为一个字符串.
a = list(String0)
print(a)
b = ''.join(a)
print(b)
[‘T’, ‘a’, ‘j’, ’ ', ‘M’, ‘a’, ‘h’, ‘a’, ‘l’, ’ ', ‘i’, ‘s’, ’ ', ‘b’, ‘e’, ‘a’, ‘u’, ‘t’, ‘i’, ‘f’, ‘u’, ‘l’]
Taj Mahal is beautiful
join( ) 也可以插入任意字符
c = '/'.join(a)[18:]
print(c)
/i/s/ /b/e/a/u/t/i/f/u/l
split( ) 可以把一个字符串拆成列表. 是对 join() 的反向操作.
d = c.split('/')
print(d)
[’ ', ‘i’, ‘s’, ’ ', ‘b’, ‘e’, ‘a’, ‘u’, ‘t’, ‘i’, ‘f’, ‘u’, ‘l’]
split( ) 还可以指定分解的次数,例如拆分3次:
e = c.split('/',3)
print(e)
print(len(e))
[’ ‘, ‘i’, ‘s’, ’ /b/e/a/u/t/i/f/u/l’]
4
lower( ) 将一个字符串里的所有大写转化为小写:
print(String0)
print(String0.lower())
Taj Mahal is beautiful
taj mahal is beautiful
upper( ) 将所有小写转为大写:
String0.upper()
‘TAJ MAHAL IS BEAUTIFUL’
replace( ) 用其他元素替代指定元素:
String0.replace('Taj Mahal','Bengaluru')
‘Bengaluru is beautiful’
strip( ) 可以去除左右两边指定的元素,例如
f = ' hello '
如果不指定,则删除左右两边的空格
f.strip()
‘hello’
strip( ) 指定删除的元素,例如要删掉星号:
f = ' ***----hello---******* '
f.strip('*')
' ***----hello---******* '
但是可以看到星号并没有被删掉,这是因为星号的两边还有空格,strip是要按照顺序来去除左右的元素的,例如我们指定先删空格再删星号:
print(f.strip(' *'))
print(f.strip(' *-'))
----hello—
hello
lstrip( ) 和 rstrip( ) 就是分别从左边或者右边删除指定元素:
print(f.lstrip(' *'))
print(f.rstrip(' *'))
----hello---*******
***----hello---
字典Dictionaries
Dictionaries字典多用来当做一个数据库来使用,因为可以通过索引来访问对应的值。
定义字典可以用 { } 或 dict()
d0 = {}
d1 = dict()
print(type(d0), type(d1))
<class ‘dict’> <class ‘dict’>
字典和列表很像,但字典可以指定一个特殊的索引,而列表只能用整数来做索引,例如:
d0['One'] = 1
d0['OneTwo'] = 12
print(d0)
{‘OneTwo’: 12, ‘One’: 1}
但首先要注意的是:
-
- 字典的索引,也就是键不能有重复值;
-
- 字典内的元素没有顺序;
d1={'One':1,'Two':2,'Three':3,'Four':4,'One':11}
print(d1)
{‘Two’: 2, ‘One’: 11, ‘Three’: 3, ‘Four’: 4}
字典的键可以是任意的“hashable”的类型(简单来说,就是需要具有__hash__()方法):
l1 = [0,1]
l2 = [2,3,4]
d1 = {l1:'length 2',l2:'length 3'}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-40-ae815677b76c> in <module>
1 l1 = [0,1]
2 l2 = [2,3,4]
----> 3 d1 = {l1:'length 2',l2:'length 3'}
TypeError: unhashable type: 'list'
可以看出,list列表不是一个hashable的类型。相对应地,tuple元组就是一个hashable的类型:
l1 = (0,1)
l2 = (2,3,4)
d1 = {l1:'length 2',l2:'length 3'}
print(d1)
{(0, 1): ‘length 2’, (2, 3, 4): ‘length 3’}
自定义的任何一个类的不同实例,默认都是hashable的:
class UserDefined():
pass
ud1 = UserDefined()
ud2 = UserDefined()
d1 = {ud1:'length 2',ud2:'length 3'}
print(d1)
{<main.UserDefined object at 0x7fe5680da588>: ‘length 2’, <main.UserDefined object at 0x7fe5680da5c0>: ‘length 3’}
现在就可以用指定的索引“one”这个字符串来访问指定的值:
print(d0['One'])
1
两个相关的列表可以合成一个字典,比如以下例子,把names列表里的元素当做键,把numbers列表里的内容当做值:
names = ['One', 'Two', 'Three', 'Four', 'Five']
numbers = [1, 2, 3, 4, 5]
zip( ) 函数可以合并两个列表:
d2 = zip(names,numbers)
print(d2)
<zip object at 0x7fe5689ba988>
d2是一个zip形式的列表,每个元素都是一个两个元素的元组,这两个元素分别来自names和numbers
接下来就可以用 dict( ) 函数把d2转化为字典:
a1 = dict(d2)
print(a1)
{‘Two’: 2, ‘One’: 1, ‘Three’: 3, ‘Five’: 5, ‘Four’: 4}
字典的内置函数
clear( ) 清除所有数据:
a1.clear()
print(a1)
{}
字典还可以通过循环来创建:
### 以下循环遍历了names和numbers,将他们逐一配对赋值给一个字典a1
for i in range(len(names)):
a1[names[i]] = numbers[i]
print(a1)
{‘Two’: 2, ‘One’: 1, ‘Three’: 3, ‘Five’: 5, ‘Four’: 4}
values( ) 返回一个由字典中的各个值组成的列表:
a1.values()
dict_values([2, 1, 3, 5, 4])
keys( ) 返回一个由字典中的各个键组成的列表:
a1.keys()
dict_keys([‘Two’, ‘One’, ‘Three’, ‘Five’, ‘Four’])
items( ) 返回字典中各个键-值对的组成的列表,在这个列表中,每一个元素是一对键和值组成的元组:
a1.items()
dict_items([(‘Two’, 2), (‘One’, 1), (‘Three’, 3), (‘Five’, 5),(‘Four’, 4)])
pop( ) 可以取出一个值再赋值给别的变量. 但是赋值的只有值,没有键:
a2 = a1.pop('Four')
print(a1)
print(a2)
{‘Two’: 2, ‘One’: 1, ‘Three’: 3, ‘Five’: 5}
4