Python学习笔记

软件和网站开发以及相关技术探讨
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

Python学习笔记

#1

帖子 oneleaf » 2006-04-22 11:31

以下是最近在学习python的一些笔记资料,希望对大家有用。
上次由 oneleaf 在 2007-11-30 20:46,总共编辑 3 次。
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

文件格式

#2

帖子 oneleaf » 2006-04-22 11:36

格式以后缀名.py结尾。
文件开头最好为:

代码: 全选

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

#3

帖子 oneleaf » 2006-04-22 11:51

字符串操作

a='单引号是字符串,\'是转义符,\n表示换行'
a="双引号中可以包含单引号'。"
a='''三个单引号'可以表示多段文字
当然,三个双引号"也是一样的效果
'''
常用函数:
find(s, sub[, start[,end]])
rfind(s, sub[, start[, end]])
index(s, sub[, start[, end]])
rindex(s, sub[, start[, end]])
count(s, sub[, start[, end]])
lower(s)
split(s[, sep[, maxsplit]])
rsplit(s[, sep[, maxsplit]])
splitfields(s[, sep[, maxsplit]])
join(words[, sep])
joinfields(words[, sep])
lstrip(s[, chars])
rstrip(s[, chars])
strip(s[, chars])
swapcase(s)
translate(s, table[, deletechars])
upper(s)
ljust( s, width)
rjust( s, width)
center(s, width)
zfill( s, width)
replace(str, old, new[, maxreplace])
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

#4

帖子 oneleaf » 2006-04-22 11:54

运算符
+ 加
- 减
* 乘
** 幂
/ 除
// 整除
% 取模
<< 左移
>> 右移
& 按位与
| 按位或
^ 按位异或
~ 按位翻转
< 小于
> 大于
<= 小于等于
>= 大于等于
== 等于
!= 不等于
not 布尔“非”
and 布尔“与”
or 布尔“或”
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

流程

#5

帖子 oneleaf » 2006-04-22 12:02

代码: 全选

if 表达式:
    ...
elif 表达式:
    ...
else:
    ...

while 表达式:
    ...
    break
    ...
    continue
else:
    ...

for i in range(1, 5):
    ...
    break
    ...
    continue
else:
    ...
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

#6

帖子 oneleaf » 2006-04-22 12:08

可一省略中间临时参数,直接交换数据。
>>> a,b,c=1,2,3
>>> a,b,c=c,a,b
>>> print a,b,c
3 1 2

字典:
>>> a={'a':1,'b':2}
>>> if a.has_key('a'):
... print a['a']
...
1

>>> print a.get('c','no found')
no found

>>> a['c']=3
>>> print a.get('c','no found')
3

>>> b={'b':4,'c':5,'d':6}
>>> for item in a.keys():
... if item in b.keys():
... print item
...
c
b

>>> print filter(b.has_key,a.keys())
['c', 'b']

>>> a={'c':3,'a':1,'b':2}
>>> b=a.keys()
>>> b.sort();
>>> print b
['a', 'b', 'c']
>>> print [a for i in b]
[1, 2, 3]

列表
>>> a=[1,2,3]
>>> b=[i+1 for i in a]
>>> print b
[2, 3, 4]

>>> b=[i for i in a if i>1]
>>> print b
[2, 3]

>>> b=[i+1 for i in a if i>1]
>>> print b
[3, 4]

>>> for i in b:print i,
...
3 4

>>> for i in range(len(b)):print i,b
...
0 3
1 4

>>> for x,y in map(None,a,b):
... print x,y
...
1 3
2 4
3 None

>>> for x,y in zip(a,b):
... print x,y
...
1 3
2 4

>>> for x,y in [(x,y) for x in a for y in b]:
... print x,y
...
1 3
1 4
2 3
2 4
3 3
3 4

>>> a=[[1,2,3],[4,5,6]]
>>> print [[b[col] for b in a] for col in range(len(a[0]))]
[[1, 4], [2, 5], [3, 6]]

>>> a=[1]*3
>>> print a
[1, 1, 1]

>>> a=[[1]*3]*2
>>> print a
[[1, 1, 1], [1, 1, 1]]

>>> import random
>>> b=['a','b','c']
>>> random.shuffle(b)
>>> print b
['c', 'b', 'a']
>>> random.shuffle(b)
>>> print b
['b', 'a', 'c']
>>> import types
>>> isinstance(b,types.ListType);
True
上次由 oneleaf 在 2006-04-22 14:25,总共编辑 6 次。
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

#7

帖子 oneleaf » 2006-04-22 13:12

字符串:

>>> for i in 'how are you':
... print i,
...
h o w a r e y o u

>>> a=list('how are you')
>>> a.sort()
>>> print a
[' ', ' ', 'a', 'e', 'h', 'o', 'o', 'r', 'u', 'w', 'y']

>>> a=2
>>> isinstance(a,type(''))
False

>>> a,b,c='2','45','6'
>>> print '|'+a.ljust(5)+'|'+b.rjust(5)+'|'+c.center(5)+'|'
|2 | 45| 6 |

>>> a=' x '
>>> print '|'+a.lstrip()+'|'+a.rstrip()+'|'+a.strip()+'|'
|x | x|x|

>>> a,b='a',['2','3','4']
>>> for i in b:
... a+=i
...
>>> print a
a234

>>> a,b='a',['2','3','4']
>>> import operator
>>> print reduce(operator.add,b,a)
a234
>>> print a+''.join(b)
a234
>>> print 1 in [c in a for c in b]
False
>>> from operator import or_
>>> reduce(or_,map(a.__contains__,b))
False

>>> a="how are you?"
>>> a=list(a)
>>> a.reverse()
>>> a=''.join(a)
>>> print a
?uoy era woh

>>> a="how are you?"
>>> a=a.split()
>>> a.reverse()
>>> a=' '.join(a)
>>> print a
you? are how

>>> import re
>>> a="how are you?"
>>> a=re.split(r'(\s+)',a)
>>> print a
['how', ' ', 'are', ' ', 'you?']
>>> a.reverse()
>>> a=''.join(a)
>>> print a
you? are how

>>> a="how are you?"
>>> print a[4:7]
are
>>> import struct
>>> format='1s 3x 2s 2x 4s'
>>> print struct.unpack(format,a)
('h', 'ar', 'you?')

>>> a="how are you?"
>>> cuts=[3,5,9]
>>> import sys
>>> print [a[i:j] for i,j in zip([0]+cuts,cuts+[sys.maxint])]
['how', ' a', 're y', 'ou?']

>>> print ord('a')
97
>>> print chr(98)
b
>>> print map(ord,'abc')
[97, 98, 99]
>>> print ''.join(map(chr,range(97,100)))
abc
头像
oneleaf
论坛管理员
帖子: 10441
注册时间: 2005-03-27 0:06
系统: Ubuntu 12.04

#8

帖子 oneleaf » 2006-04-22 16:41

文件
>>> all=open('.bashrc').read()
>>> print all[:11]
# ~/.bashrc

>>> file=open('.bashrc')
>>> lines=file.readlines()
>>> print lines[0]
# ~/.bashrc: executed by bash(1) for non-login shells.

>>> file=open('.bashrc')
>>> lines=file.read().splitlines()
>>> print lines[0]
# ~/.bashrc: executed by bash(1) for non-login shells.

>>> file=open('.bashrc')
>>> lines=file.read().split('\n')
>>> print lines[0]
# ~/.bashrc: executed by bash(1) for non-login shells.

>>> file=open('.bashrc')
>>> lines=list(file)
>>> print lines[0]
# ~/.bashrc: executed by bash(1) for non-login shells.

>>> file=open('.bashrc')
>>> for line in file:
... print line
... break
...
# ~/.bashrc: executed by bash(1) for non-login shells.

>>> file=open('.bashrc')
>>> while 1:
... line=file.readline()
... print line
... if not line:break
... break
...
# ~/.bashrc: executed by bash(1) for non-login shells.
>>> file.close()

>>> file=open('test.txt','r+w')
>>> file.write('how are you')
>>> file.close()
>>> file=open('test.txt')
>>> print file.read()
how are you

>>> file=open('test.txt','r+w')
>>> file.write(file.read().upper())
>>> file.close()
>>> file=open('test.txt')
>>> print file.read()
how are youHOW ARE YOU

>>> import linecache
>>> print linecache.getline('.bashrc',1)
# ~/.bashrc: executed by bash(1) for non-login shells.

>>> random.choice(open('.bashrc').readlines())
'# sources /etc/bash.bashrc).\n'

>>> count=0
>>> for line in open('.bashrc'): count += 1
...
>>> print count
72
>>> print len(open('.bashrc').readlines())
72

>>> for line in open('test.txt'):
... for word in line.split():
... print word
...
how
are
youHOW
ARE
YOU

>>> import os
>>> print os.path.split('/usr/bin/python')
('/usr/bin', 'python')
>>> print os.path.normpath('/usr//bin//python')
/usr/bin/python
>>> print os.path.join(sys.prefix,'test.txt')
/usr/test.txt

>>> os.makedirs('/tmp/abc/abc',0777)

>>> from os import walk
>>> def listdir(path):
... listfiles=[]
... for root, dirs, files in walk(path):
... for file in files:
... listfiles.append(btfile)
... return listfiles
...
>>> print listdir('/tmp')

>>> print os.path.exists('/usr/bin/python')
True

>>> print os.path.isdir('/usr/bin/python')
False

>>> print os.listdir('/usr')
['share', 'bin', 'doc', 'games', 'include', 'lib', 'sbin', 'src', 'local', 'man', 'X11R6', 'lib64', 'libexec']

>>> print os.path.splitext('test.txt')
('test', '.txt')

>>> import ConfigParser
>>> import string
>>> config = {}
>>> cp = ConfigParser.ConfigParser()
>>> cp.read('.mozilla/firefox/profiles.ini')
['.mozilla/firefox/profiles.ini']
>>> for sec in cp.sections():
... name = string.lower(sec)
... for opt in cp.options(sec):
... config[name + "." + string.lower(opt)] = string.strip(cp.get(sec, opt))
...
>>> print config
{'profile0.path': 'zituwy0x.default', 'profile0.name': 'default', 'profile0.isrelative': '1', 'general.startwithlastprofile': '1'}
taoyh
帖子: 108
注册时间: 2005-09-26 19:26

#9

帖子 taoyh » 2006-05-02 0:09

像这种东西,最好放在wiki里。
suave
帖子: 34
注册时间: 2005-09-05 12:09
来自: Peking
联系:

#10

帖子 suave » 2006-05-11 17:28

oneleaf兄,这么好的东西我觉得最好有时间再把它写的完整一点,浅显易懂一些。这么看还是觉得太抽象了,会吓倒一片~我觉得linux下面的perl manual写的就很是不错,可以参考。

man perl
man perlintro
...
cosmostail
帖子: 24
注册时间: 2006-05-25 5:52

#11

帖子 cosmostail » 2006-06-04 1:06

PYTHON 一点都不难。用PYTHON写的CODE 清爽易读。这一点PERL是无法比地。
tcftt
帖子: 22
注册时间: 2006-04-24 11:37

#12

帖子 tcftt » 2006-06-05 11:09

python对格式要求蛮严格的,呵呵呵
头像
peakgg
帖子: 1122
注册时间: 2006-10-10 9:40

#13

帖子 peakgg » 2007-01-08 20:57

一叶大人应该把代码code了啊,这样看不出缩进。
命令行提示不管几级都是...
为什么不是每加一级自动填tab呢?
这就是传说中的强制习惯么?
头像
huangjiahua
帖子: 3294
注册时间: 2005-03-30 0:27
联系:

#14

帖子 huangjiahua » 2007-03-10 18:23

楼上,命令行交互推荐用 ipython

代码: 全选

In [1]: def a(s):
   ...:     for i in s:
   ...:         print i,
   ...:         
   ...:         

In [3]: a('12345')
1 2 3 4 5

In [4]: a.
a.__call__          a.__getattribute__  a.__reduce__        a.func_code
a.__class__         a.__hash__          a.__reduce_ex__     a.func_defaults
a.__delattr__       a.__init__          a.__repr__          a.func_dict
a.__dict__          a.__module__        a.__setattr__       a.func_doc
a.__doc__           a.__name__          a.__str__           a.func_globals
a.__get__           a.__new__           a.func_closure      a.func_name

In [4]: a.
也支持 Tab 键补全
跃过无数的时间断层,只为了在
头像
peakgg
帖子: 1122
注册时间: 2006-10-10 9:40

#15

帖子 peakgg » 2007-03-18 17:26

谢谢楼上^_^
回复