Notes for Introducing Python¶
本文档是阅读 “Introducing Python” 一书所做的笔记.
- 在线阅读地址: http://introducing-python-notes.readthedocs.io/
- Github 上项目主页为: https://github.com/CarlKing5019/introducing-python-notes
人生苦短, 我用 Python!
第一章 Python 初探¶
The Zen of Python¶
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
第二章 Python 基本元素¶
本章从 Python 最基本的内置数据类型开始学习, 这些类型包括:
- 布尔型:
class 'bool'
, 仅包含 True, False 两个值 - 整型:
<class 'int'>
- 浮点型:
<class 'float'>
- 字符串型:
<class 'str'>
2.1 变量, 名字和对象¶
Python 是强类型的, 永远无法修改一个已有对象的类型, 即使它包含的值是可变的. 但可以给一个变量赋不同于其值的类型的值. 举个例子, 以下代码在 Python 中是合法的.
>>> a=123
>>> a
123
>>> a='abc'
>>> a
'abc'
Python 中变量名命名规则
- 只能包含以下字符:
[a-zA-Z0-9_]
; - 不允许以数字开头;
- 以下划线开头的名字有特殊含义.
Python 中的保留字
True class finally is return
False continue for lambda try
None def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
2.2 数字¶
Python 中支持的数学运算符如下:
+ # 加法
- # 减法
* # 乘法
/ # 浮点数除法 (转换为浮点数相除, 并得到浮点数结果)
// # 整数除法 (返回商)
% # 模 (返回余数)
** # 幂 (这个比较奇葩, 咋不用 ^ 呢)
类型转换¶
使用 int()
函数可以将布尔型, 整型, 或者浮点数,
或者由数字组成的字符串转换为整数. 对于布尔型转换为 1 或 0, 对于浮点数返回其整数部分.
>>> int(True)
1
>>> int(False)
0
>>> int('99')
99
>>> int('-23')
23
>>> int('+12')
12
>>> int(98.6)
98
>>> int(1.0e4)
10000
>>> int('98.6')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '98.6'
>>> int('1.0e4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.0e4'
小技巧
Mac 终端中 Python 交互界面下的清屏快捷键是 Command+K
,
比其他系统下方便多了.
小技巧
Python 3 中 int 类型可以存储 任意大小 的整数.
浮点数¶
使用 float()
函数可以将布尔型, 整型,
或包含有效整数或有效浮点数的字符串转换为浮点型.
>>> float(True)
1.0
>>> float(False)
0.0
>>> float(98)
98.0
>>> float('99')
99.0
>>> float('98.6')
98.6
>>> float('-1.5')
-1.5
>>> float('1.0e4')
10000.0
>>>
2.3 字符串¶
注解
对 Unicode 的支持使得 Python 3 可以包含世界上任何书面语言以及许多特殊符号。
使用引号创建字符串¶
在 Python 中可以使用一对 '
, "
, '''
, """
来创建字符串.
三元引号中的换行符无需转义, 多用于创建多行字符串.
在三元引号包裹的字符串中, 每行的换行符以及行首或行末的空格都会被保留.
举个例子:
>>> s = '''a
... b
... c
... d'''
>>> s
'a\nb\nc\nd'
>>> print(s)
a
b
c
d
警告
三元引号包裹的字符串并不是原样输出, 只是换行符无需转义, 但转义仍然是起作用的.
注解
在引号中不包含任何字符即可以创建一个空串.
使用 str()
进行类型转换¶
使用 str() 函数可以将其他 Python 数据类型转换为字符串:
>>> str(98.6)
'98.6'
>>> str(1.0e4)
'10000.0'
>>> str(True)
'True'
当调用 print() 函数或者进行字符串差值(string interpolation)时,Python 内部会自动 使用 str() 将非字符串对象转换为字符串。
使用 \
转义¶
换行符: \n
, 制表符: \t
, 引号也可以进行转义, \'
, \"
.
使用 +
拼接字符串¶
在 Python 中,可以使用 +
将多个字符串或字符串变量拼接起来:
>>> 'Release the kraken! ' + 'At once!'
'Release the kraken! At once!'
使用 *
复制字符串¶
>>> test = 'ha' * 4 + 'wa' * 3
>>> test
'hahahahawawawa'
使用 []
提取字符¶
使用 string[index]
可以提取字符串 string
中 index
位置的单个字符. 注意: 0 表示第一个字符, 1 表示第二个字符, ... , -1
表示最后一个字符.
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[0]
'a'
>>> letters[1]
'b'
>>> letters[-1]
'z'
>>> letters[-2]
'y'
注解
位置索引在其他序列类型, 如列表和元组中的用法也是这样.
警告
字符串是不可变的, 无法通过给 string[index]
赋值的方式改变字符串的值.
使用切片 [start:end:step]
提取字符串¶
切片操作 (slice) 可以从一个字符串中提取子字符串. [start:end:step]
称为一个切片, 得到的子串包含从 start
到 end
之前的间隔为
step
的全部字符. 三个参数的值都是可以省略的, 如果省略 start
默认从开头提取; 省略 end
默认提取到结尾; 省略 step
默认步长为 1.
常用的切片操作及其含义如下:
[:]
提取从开头到结尾的整个字符串.[start:]
提取从start
到结尾的字符串.[:end]
提取从开头到end-1
的字符串.[start:end]
提取从start
到end-1
的字符串.[start:end:step]
提取从start
到end-1
间隔为step
的字符串.[::step]
提取从开头到结尾, 步长为step
的字符串
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[:]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[7:]
'hijklmnopqrstuvwxyz'
>>> letters[:-3]
'abcdefghijklmnopqrstuvw'
>>> letters[7:-3]
'hijklmnopqrstuvw'
>>> letters[::2]
'acegikmoqsuwy'
>>> letters[7:-3:2]
'hjlnprtv'
>>> letters[7::2]
'hjlnprtvxz'
>>> letters[:20:2]
'acegikmoqs'
注解
如果步长为负数, 则从右到左反向进行提取操作.
>>> letters[-1::-1]
'zyxwvutsrqponmlkjihgfedcba'
>>> letters[::-1]
'zyxwvutsrqponmlkjihgfedcba'
>>> letters[0::-1]
'a'
注解
切片操作对于无效偏移量的容忍程度远大于单字符串提取. 如果在切片对应的索引位置不存在字符, 也不会报错, 而是返回空字符.
>>> letters[-50:]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[-50:-40]
''
>>> letters[:70]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[60:70]
''
使用 len()
获取长度¶
>>> len(letters)
26
>>> len('')
0
注解
也可以对其他的序列类型使用 len()
.
警告
len()
是函数, 而不是字符串的方法.
Last update: Jul 6, 2017
小技巧
使用 type(x)
可以查看 x
的类型.