python学习总结

字符串操作

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])

运算符
+ 加
- 减
* 乘
** 幂
/ 除
// 整除
% 取模
<< 左移
>> 右移
& 按位与
| 按位或
^ 按位异或
~ 按位翻转
< 小于
> 大于
<= 小于等于
>= 大于等于
== 等于
!= 不等于
not 布尔“非”
and 布尔“与”
or 布尔“或”

控制语句

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

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

for i in range(1, 5):
     ...
     break
     ...
     continue
else:

可一省略中间临时参数,直接交换数据。
>>> 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[i] 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[i]
...
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

字符串:

>>> 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(97)
b
>>> print map(ord,'abc')
[97, 98, 99]
>>> print ''.join(map(chr,range(97,100)))
abc

 

文件
>>> 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'}

&&&本文摘自:http://apps.hi.baidu.com/share/detail/19550806

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值