######################### ---python简单学习
(1)语句块缩进
缩进表达一个语句属于哪个代码块
4个空格最佳
(2)程序输出
python
>>>print 'hello world'
hello world
>>>print 'hello'+'world' #+把两个字符串合在一块
helloworld
>>>print 'hello','world' #python中,表示空格
hello world
(3)程序输入
>>>raw_input('enter your name: ') #相当于shell 里面 read -p
enter your name:
(4)文档字符串
"" '' python中 这两者无区别
>>>''' input '''/""" 较长文字说明可以使用三引号,转行
aaa'''
input
aaa
(5)数据类型
数字:int(有符号整数)long(长整数)True:1 False:0 float(浮点数)
默认十进制 0开头八进制/0x 16进制 /0b 2进制
字符串 被定义为引号之间的字符集合
>>>name = '123' 此时123不是数字
>>>name[0] 字符串切片0开始,最后一个-1
'1'
>>>name[0:2] 不包含结束下标(起始不包含)
'12'
>>>name *2 *将一个字符串重复多次
'123123'
列表 相当于普通的数组,保存任意数量类型的python对象
>>>alist=[1,"abc",2,[1,2]]
>>>alist[1]
"abc"
>>>'abc' in alist 判断是否在列表中
True
>>>'bb' not in alist
True
>>>alist.append(3) 追加新的元素3
[1,"abc",2,[1,2],3]
>>>alist[0]=100 重新赋值
元组 静态的列表,不可变
>>>atuple=(1,"aa",3)
不可追加,不可重新赋值
字典 由key-value对构成映射数据类型
>>>result={'name':'bob","age":'23'}
字典也是可变的
>>>result['gender']='male'
{'name':'bob","age":'23','gender':'male'}
当不存在key时,会新建,存在时,重新赋值
########################################
循环
range(3) 相当于shell seq 3 (1 2 3)
0,1,2
for 常与range连用
continue 结束此次循环
break 从这个循环中跳出来
else 不同于if 里面的else, 当循环被break中断后,不执行else下的程序
只有循环完整结束才执行
fobj=open('/etc/passwd' 'r'(默认)) 文件打开方法: 'w'写入方式打开,文件存在则清空其内容,不存在,新建 'a'追加写入
data=fobj.read() 文件输入 readline 读一行 readlines 读剩下的所有,并以字符串列表返回
print data
fobj.close()
文件迭代 结合for循环
fobj=open('/etc/passwd')
for line in fobj
print line 逐行读
文件输出
fobj=open('/etc/passwd')
fobj.write('hello world\n') \n换行
fobj.writelines['hello world\n','python is good\n'] writelines 以列表为参数写入
模拟copy
思路,把源文件读取后写入新的文件
src_fobj=open('/etc/passwd')
dst_fobj=open('/opt/passwd','w')
data=src_fobj.read(4096) 一次读4096个字节
if data=='': 一次读完后,光标停留在当前为值,下次读,则继续从此开始向下读
break 读完后,光标停留在末尾,此时读取的数据为''
dst_fobj.write(data)