用了两天时间读了一本Python的书,算是入门书吧。 确实写得很好。 这篇博客仅作为读书笔记。 PDF也已上传,下载地址:
http://download.csdn.net/detail/ch717828/9815193
版本为python 3.x
为什么选择Python
那些最好的程序员不是为了得到更高的薪水或者得到公众的仰慕而编程,它们只是觉得这是一件有趣的事 --Linux Torvalds
现在就开始
Mac上安装Python 3.x
Mac默认自带的Python版本为2.7 ,需要安装最新的Python 3.6
- 下载 : https://www.python.org/downloads/release/python-361/
- 直接打开安装包安装即可
- 检查 : 控制台输入python3
安装IDE
选择pycharm
- 下载 :
https://www.jetbrains.com/pycharm/download/#section=mac - 安装下载的安装包
变量与字符串
Python对大小写敏感,第一个helloword例子:
#!/usr/local/bin/python3
print("Hello, World!");
使用type()函数可以查看变量类型
#!/usr/local/bin/python3
#coding=utf-8
num = 1;
str = "2";
print(type(num)); #打印类型
print(type(str));
由于中文注释会导致报错,因此在文件开头加上一行 #coding=utf-8
字符串与数字的操作:
#!/usr/local/bin/python3
#coding=utf-8
num = 5;
str1 = "2";
str2 = "a";
print(str1*num);
print(str2*num);
print(int(str1)+num);
运行结果:
22222
aaaaa
7
字符串的分片与索引
字符串可以通过string[x]的方式进行索引、分片。字符串的分片(slice)实际上可以看作是从字符串中找出你要截取的东西,复制出来一小段你要的长度,存储在一个地方,而不会对字符串这个源文件改动。分片获得的每个字符串可以看作是原字符串的一个副本。
#!/usr/local/bin/python3
#coding=utf-8
name = "My Name is Mike";
print(name[0]); #M
print(name[-4]); #M
print(name[11:14]); #Mik
print(name[11:15]); #Mike
print(name[5:]); #me is Mike
print(name[:5]); #My Na
字符串方法
- replace()
#!/usr/local/bin/python3
#coding=utf-8
phone_number = "86147-621-42214";
hiding_number = phone_number.replace(phone_number[:9],"*"*9);
print(hiding_number)
- find()
#!/usr/local/bin/python3
#coding=utf-8
search = '168';
num_a = '1386-168-0006';
num_b = '1681-222-0006';
print(search+" is at "+str( num_a.find(search))+" to "+str(num_a.find(search)+len(search))+" of num_a");
print(search+" is at "+str( num_b.find(search))+" to "+str(num_b.find(search)+len(search))+" of num_b");
- format()
#!/usr/local/bin/python3
#coding=utf-8
#With a word she can get what she come
print("{} a word she can get what she {} for.".format('With','came'));
print("{preposition} a word she can get what she {verb} for.".format(preposition='With',verb='came'));
print("{0} a word she can get what she {1} for.".format('With',"came"));
函数
- 创建一个函数并调用
#!/usr/local/bin/python3
#coding=utf-8
def default_parameter(arg1,arg2,arg3=