python小知识点总结

Python API : http://download.csdn.net/detail/huangzebiao007/7249149

一、print格式化输出

print "%s is number %d!" % ("Python", 1)

print “A”,"B"

二、内建函数raw_input()

user = raw_input('Enter login name: ')

将输入的值赋值给变量user

三、内建函数int()

int("12")

将字符串转换为整数

四、运算符

+ - * / % **(乘方)

五、逻辑运算符

and or not

六、比较运算符

< <= > >= == != <>(该不等于不推荐使用)

七、序列类型操作符

序列类型是指字符串,列表,元组

成员关系操作符 (in, not in)

序列操作符      作用
seq[ind]        获得下标为ind 的元素
seq[ind1:ind2]  获得下标从ind1 到ind2 (不包括ind2)间的元素集合
seq * expr      序列重复expr 次
seq1 + seq2     连接序列seq1 和seq2
obj in seq      判断obj 元素是否包含在seq 中
obj not in seq  判断obj 元素是否不包含在seq 中

八、序列的切片操作

s[(1):(2):(3)]

(1)代表起始索引

(2)代表结束索引

(3)代表切片的方向和步伐 正数代表向右方向,负数代表向左方向,数字大小代表步伐

s = 'abcdefgh'

对应的索引下标是 0  1  2  3  4  5  6  7

                -8 -7 -6 -5 -4 -3 -2 -1  

s[::-1]

'hgfedcba'

s[::2]

'aceg'

s[0:3:2]

'ac'

s[0::3]

'adg'

s[-1:-3:-1]

'hg'

s[-1:-9:-1]

'hgfedcba'

s[-1:-9:1]

''

s[-8:2:1]

'ab'

s[-8:-6:1]

'ab'

九、序列类型可用的内建函数

函数名                                                    功能
enumerate(iter)                                    接受一个可迭代对象作为参数,返回一个enumerate 对象(同时也是一个迭代器),该对象生成由iter 每个元素的index 值和item 值组成的元组
for u in enumerate(s):
print u
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
(6, 'g')
(7, 'h')


len(seq)                                                 返回seq 的长度


max(iter,key=None) or
max(arg0,arg1...,key=None)              返回iter 或(arg0,arg1,...)中的最大值,如果指定了key,这个key 必须是一个可以传给sort()方法的,用于比较的回调函数.


min(iter, key=None) or
min(arg0, arg1.... key=None)            返回iter 里面的最小值;或者返回(arg0,arg2,...)里面的最小值;如果指定了key,这个key 必须是一个可以传给
sort()方法的,用于比较的回调函数.

reversed(seq)                                      接受一个序列作为参数,返回一个以逆序访问的迭代器

for v in reversed(s):
print v
h
g
f
e
d
c
b
a


sorted(iter,func=None,

key=None,reverse=False)                  接受一个可迭代对象作为参数,返回一个有序的列表;可选参数func,key 和reverse 的含义跟list.sort()内建函数的参数含义一样.

sum(seq, init=0)                                   返回seq 和可选参数init 的总和

十、字符串

Python 中字符串被定义为引号之间的字符集合。Python 支持使用成对的单引号或双引号,三引号(三个连续的单引号或者双引号)可以用来包含特殊字符。

使用索引运算符( [ ] )和切片运算符( [ : ] )可以得到子字符串。字符串有其特有的索引规则:第一个字符的索引是 0,最后一个字符的索引是 -1

加号( + )用于字符串连接运算,星号( * )则用于字符串重复。

字符串的常用方法查看API文档

十一、读取配置文件

import ConfigParser
cf = ConfigParser.ConfigParser()
cf.read("F:\\eclipseForPythonWorkSpace\\LogHandlePython\\src\\DBConfig.properties")
db = cf.options("db")
url = cf.get('db','url')
users = cf.get('db','user')
password = cf.get('db','password')


DBConfig.properties:

[db]
url = localhost
user = root
password = root

十二、得到前一天的日期 :2014-04-24

import datetime

time = datetime.date.today() - datetime.timedelta(days=1)

十三、lambda函数

Python允许你定义一种单行的小函数。定义lambda函数的形式如下:labmda 参数:表达式lambda函数默认返回表达式的值。你也可以将其赋值给一个变量。lambda函数可以接受任意个参数,包括可选参数,但是表达式只有一个:
>>> g = lambda x, y: x*y
>>> g(3,4)
12
>>> g = lambda x, y=0, z=0: x+y+z
>>> g(1)
1
>>> g(3, 4, 7)
14
也能够直接使用lambda函数,不把它赋值给变量:
>>> (lambda x,y=0,z=0:x+y+z)(3,5,6)
14

十四、Python是如何进行类型转换的

Python提供了将变量或值从一种类型转换成另一种类型的内置函数。int函数能够将符合数学格式数字型字符串转换成整数。否则,返回错误信息。
>>> int(”34″)
34
>>> int(”1234ab”) #
不能转换成整数
ValueError: invalid literal for int(): 1234ab
函数int也能够把浮点数转换成整数,但浮点数的小数部分被截去。
>>> int(34.1234)
34
>>> int(-2.46)
-2
函数°oat将整数和字符串转换成浮点数:
>>> float(”12″)
12.0
>>> float(”1.111111″)
1.111111
函数str将数字转换成字符:
>>> str(98)
‘98′
>>> str(”76.765″)
‘76.765′
整数1和浮点数1.0python中是不同的。虽然它们的值相等的,但却属于不同的类型。这两个数在计算机的存储形式也是不一样。

十五、如何反序的迭代一个序列

如果是一个list, 最快的解决方案是:list.reverse()

try:
for x in list:
“do something with x”
finally:
list.reverse()

如果不是list, 最通用但是稍慢的解决方案是:

for i in range(len(sequence)-1, -1, -1):
x = sequence[i]
<do something with x>

十六、range()函数的用法:得到一个list(注意区分开跟切片相关的操作(切片是有负数代替,而range()生成的列表则完全是根据数字来着))

This is a versatile function to create lists containing arithmetic progressions. It is most often used infor loops. The arguments must be plain integers. If thestep argument is omitted, it defaults to1. If thestart argument is omitted, it defaults to0. The full form returns a list of plain integers[start,start+step,start+2*step,...]. Ifstep is positive, the last element is the largeststart+i*step less thanstop; ifstep is negative, the last element is the smalleststart+i*step greater thanstop.step must not be zero (or elseValueError is raised). Example:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
十七、Python里面如何实现tuple和list的转换

tuple([1,2,3])返回(1,2,3)

list((1,2,3))返回[1,2,3]

十八、删除一个list里面的重复元素

可以先把list重新排序,然后从list的最后开始扫描

List.sort()
last = List[-1]
for i in range(len(List)-2, -1, -1):
if last==List[i]: del List[i]
else: last=List[i]

十九、random

>>> random.random()        # Random float x, 0.0 <= x < 1.0
0.37444887175646646
>>> random.uniform(1, 10)  # Random float x, 1.0 <= x < 10.0
1.1800146073117523
>>> random.randint(1, 10)  # Integer from 1 to 10, endpoints included
10
>>> random.randrange(1, 10)  #  1 <= x < 10
9
>>> random.randrange(1, 20, 2) 1
11
13
15
7
>>> random.choice('abcdefghij')  # Choose a random element
'c'

>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[7, 3, 2, 5, 6, 4, 1]

>>> random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
[4, 1, 5]

二十、包裹传递

定义函数时,我们有时候并不知道调用的时候会传递多少个参数。这时候,包裹(packing)位置参数,或者包裹关键字参数,来进行参数传递,会非常有用。

def func(*name):
    print type(name)
    print name

func(1,4,6)
func(5,6,7,1,2,3)
两次调用,尽管参数个数不同,都基于同一个func定义。在func的参数表中,所有的参数被name收集,根据位置合并成一个元组(tuple),这就是包裹位置传递。

def func(**dict):
    print type(dict)
    print dict

func(a=1,b=9)
func(m=2,n=1,c=11)

def func(a,b,c):
    print a,b,c

args = (1,3,4)
func(*args)

dict = {'a':1,'b':2,'c':3}
func(**dict)

二十一、数据库操作

http://www.cnblogs.com/rollenholt/archive/2012/05/29/2524327.html

二十二、str.translate(table[,deletechars])string.maketrans(from,to) 

translate的功能是先删除掉deletechars里面的字符,然后再根据table的映射关系转换字符

先看个例子:

str = "abcdefg12345"
print str.translate(None,"efg45")
输出结果:

abcd123

因为table=None,所以只删除掉字符,要使用table,就要靠string.maketrans(from,to),该函数的返回结果是一个table:

import string

str = "hzb123ah."

table=string.maketrans('hzb','HZB')

print str.translate(table)
输出结果:

HZB123aH.

二十三、pickle存储对象和还原对象

import pickle
class Person:
    def __init__(self,n,a):
        self.__name=n
        self.__age=a
    def show(self):
        print self.__name+"_"+str(self.__age)
aa = Person("hzb", 24)
aa.show()
f=open('d:\\people.p','w')
pickle.dump(aa,f)
f.close()
import pickle
class Person:
    def __init__(self,n,a):
        self.__name=n
        self.__age=a
    def show(self):
        print self.__name+"_"+str(self.__age)
f=open('d:\\people.p','r')
bb=pickle.load(f)
f.close()
bb.show()

二十四、python group()

正则表达式中,group()用来提出分组截获的字符串,()用来分组

import re
a = "123abc456"
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0)   #123abc456,返回整体
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1)   #123
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2)   #abc
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3)   #456

1. 正则表达式中的三组括号把匹配结果分成三组

  •  group() 同group(0)就是匹配正则表达式整体结果
  •  group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3) 列出第三个括号匹配部分。

2. 没有匹配成功的,re.search()返回None

3. 当然正则表达式中没有括号,group(1)肯定不对了。


二十五、date

# -*- coding: utf-8 -*-
from datetime import *
import time
# 1. date常用的类方法和类属性

#date对象所能表示的最大日期: 9999-12-31
print 'date.max',date.max
#date对象所能表示的最小日期: 0001-01-01
print 'date.min',date.min
#返回一个表示当前本地日期的date对象: 2012-09-12
print 'date.today():', date.today()  
#将Gregorian日历时间转换为date对象(Gregorian Calendar :一种日历表示方法,类似于我国的农历,西方国家使用比较多): 
#1347442385.972转换为2012-09-12
print 'date.fromtimestamp():', date.fromtimestamp(time.time()) 

# 2. date提供的实例方法和属性

#获得年 月 日
now = date(2012,9,17)
print 'now.year:',now.year
print 'now.month:',now.month
print 'now.day:',now.day
#date.replace(year, month, day):生成一个新的日期对象
#用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变)
tomorrow = now.replace(day = 18)
nextmonth = now.replace(month = 10)
nextyear = now.replace(year = 2013)
print "tomorrow:",tomorrow," nextyear:",nextyear," nextmonth:",nextmonth
# 返回日期对应的time.struct_time对象;
# print: time.struct_time(tm_year=2012, tm_mon=9, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=261, tm_isdst=-1)
print "date.timetuple(): ",now.timetuple() 
# 返回日期对应的Gregorian Calendar日期;
#print: 734763
print "date.toordinal(): ",str(now.toordinal())
#返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推; 
#print:0
print "date.weekday(): ",now.weekday()
#返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;
#print: 1
print 'date.isoweekday(): ',now.isoweekday() 
#返回格式如(year,month,day)的元组;
#print: (2012, 38, 1)
print 'date.isocalendar():',now.isocalendar() 
#返回格式如'YYYY-MM-DD’的字符串;
#print: '2012-09-17'
print 'date.isoformat():',now.isoformat()
#date.strftime(fmt):自定义格式化字符串。在下面详细讲解。

#3. 日期操作 

#当前日期为2012年9月12日
now = date.today()
tomorrow = now.replace(day = 13)
delta = tomorrow - now
print "now: ",now,"tomorrow: ",tomorrow
#计算出间隔时间
#print: timedelta:  1 day, 0:00:00
print "timedelta: ",delta
#print: now + delta = tomorrow : 2012-09-13
print "now + delta = tomorrow :",now + delta
#print: tomorrow > now : True
print "tomorrow > now :",tomorrow > now
#print: tomorrow < now : False
print "tomorrow < now :",tomorrow < now


二十六、列表解析

[x for x in range(5)]

[0, 1, 2, 3, 4]

[x for x in range(5) if x > 2]

[3, 4]


dicts = {1:'a',2:'b'}

[ (k,v) for (k, v) in dicts.items()]

[(1, 'a'), (2, 'b')]

[ (k,v) for k, v in dicts.items()]

[(1, 'a'), (2, 'b')]

[ [k,v] for (k, v) in dicts.items()]

[[1, 'a'], [2, 'b']]


二十七、重写__call__函数

Python中有一个有趣的语法,只要定义类的时候,实现__call__函数,那么这个类的对象就成为可调用的,调用时候是调用了__call__函数。换句话说,我们可以把这个类型的对象当作函数来使用

class Functor:
    def __init__(self, func, args):
        self.func = func
        self.args = args


    def __call__(self, args):
        self.func(self.args , args)
        
def abc(a, b):
   print a, b
   
f = Functor(abc,1)
f(2)//这里调用了call方法


输出1 2


二十八、查找文件中的中文

http://bbs.csdn.net/topics/310017410









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值