1. 第一个Python程序
命令行退出Python
exit()
数学运算
100 + 200
打印
print('打印内容')
单引号或双引号皆可。
1.1 使用文本编辑器
命令窗口执行Python文件
python test.py
1.2 Python代码运行助手
1.3 输入和输出
输出
print('输出内容')
或者
print('内容1','内容2')
逗号相当于一个空格。
输入
name = input(输入name:)
输入后转换类型
s = input('birth: ')
birth = int(s)
2. Python基础
2.1 数据类型和变量
转义字符
符号 | 内容 |
---|---|
’ | ’ |
" | " |
\n | 换行 |
\t | 制表 |
\ | \ |
r’’ | ''内不转义 |
print(’’’…’’’) | 换行 |
%% | % |
除法
符号 | 含义 |
---|---|
a/b | 精确除 |
a//b | 取整 |
a%b | 取余 |
2.2 字符串和编码
字符转编码(Unicode)
ord('A')
编码转字符
chr('65')
整数编码
'\u4e2d\u6587'
等价于
'中文'
bytes类型数据表示
x = b'ABC'
str转bytes
'ABC'.encode('ascii')
'中文'.encode('utf-8')
bytes转str
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'
忽略错误字节
>>> b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')
'中'
计算str包含多少个字符
>>> len(b'ABC')
3
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')
6
>>> len('中文'.encode('utf-8'))
6
包含中文的*.py文件开头注释
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
格式化
>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
占位符
占位符 | 替换内容 |
---|---|
%d | 整数 |
%f | 浮点数 |
%s | 字符串 |
%x | 十六进制数 |
补零和位数
print('%2d-%05d' % (3, 1))
print('%.2f' % 3.1415926)
结果:
3-00001
3.14
format
>>> 'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)
'Hello, 小明, 成绩提升了 17.1%'
2.3 list和tuple
2.3.1 list
>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']
获取list中元素的个数
>>> len(classmates)
3
访问list中某个元素
>>> classmates[0]
'Michael'
或者
>>> classmates[-1]
'Tracy'
list末尾追加元素
classmates.append('Adam')
插入到指定的位置,比如索引号为1的位置:
>>> classmates.insert(1, 'Jack')
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
删除list某元素
classmates.pop(1) //删除指定
classmates.pop() //删除末尾
替换list某元素
直接赋值
一个list可有不同类型元素
list可多维可空
2.3.2 tuple
与list相比,[]改成()
不可修改
1个元素时
>>> t = (1,)
>>> t
(1,)