1.基本数据类型: 字符串、整数、小数、bool
2.基本语法(以python3.0为准)
//输入
input();
//得到输入的值
value=eval(input());
//得到一个数字
value=int(input());
//输出
print();
print('%d is a num' %4);
print('%s' is a string'%string);
print('price is %.2f' %4.99)
//条件
if a == 1:
print 'one'
elif a == 2:
print 'two'
elif a == 3:
print 'three'
else:
print 'too many'
//循环
while condition:
sentence;
for i in range(1,10):
print i
//函数
def plus(num1, num2):
print num1+num2
3.python类型转换
int(x) #把x转换成整数
float(x) #把x转换成浮点数
str(x) #把x转换成字符串
bool(x) #把x转换成bool值
(在python中,其他类型转成 bool 类型时,以下数值会被认为是False:为0的数字,包括0,0.0 空字符串,包括'',"" 表示空值的None 空集合,包括(),[],{} 其他的值都认为是True。)
4.list相关操作
- 索引
- 增:list.append()
- 删:del list[0]
- 改:list[1]=2
- 切片
- I[1:3],I[-1],
5.字符串的分割
sentence='I am a English. sentence'
sentence.split();
sentence.split('.');
sentence.split('a');
6.字符串的连接
s=';'
s.join(['hello','world']);
7.list与字符串的区别
索引和切片操作类似,但是字符串不能更改索引位置的值
8.读写文件
//打开文件
f = open('data.txt');
//读取文件
data=f.read();
//打印文件
print data
//关闭文件
f.close()
//补充
readline() #读取一行内容
readlines() #把内容按行读取至一个list中
9.写文件
f=open('output.txt','w') //w写模式 ,默认为r模式,还有'a'模式
,但是写入的内容不会覆盖之前的内容,而是添加到文件中
示例程序
data='I whill be in a file.\n So cool!'
out=open('output.txt','w')
out.write(data)
out.close()
10 .异常处理
try:
f=open('non-exist.txt')//可能出现问题的语句
print('file open')
f.close()
except:
print ('file not exists')//出现问题后如何处理
11.字典
基本格式 d={key1:value1,key2:value2}
注意键只能是字符串、整数、浮点数,bool值等简单对象
访问字典中元素的方法:
score.get('abc')
遍历字典中的元素
for name in score:
print srcore[name]
改变某一项的值则直接给这一项赋值
score['雾霾']=91
删除一项字典项的方法:
del score['萧峰']
12.正则表达式
*任意数量字符,匹配最长结果,.*?匹配最短的结果
\S 表示不是空白符的任意字符
[0-9]内任意一个字符 匹配任意长度数字,用[0-9]* 或者 \d*
\d{11}限制长度为11
1\d{11}第一位限定为1