去除空格
方法一:使用字符串
#!/usr/bin/env python
whitespace = ' vf'
def myStrip(chs):
pass
def myLstrip(chs):
if len(chs) ==0:
return chs
strlen = len(chs)
for i in range(strlen):
if chs[i] not in whitespace:
break
else:
return ''
return chs[i:]
def myRstrip(chs):
if len(chs) == 0:
return chs
strlen =len(chs)
for i in range(-1, -(strlen + 1), -1):
if chs[i] not in whitespace:
break
else:
return ''
return chs[:i + 1]
if __name__ == '__main__':
myStr = ' hello '
print '|' + myStr + '|'
# print '|' + myStrip[myStr] + '|'
print '|' + myLstrip(myStr) + '|'
print '|' + myRstrip(myStr) + '|'
方法二:使用列表
#!/usr/bin/env python
whitespace = ' vf'
def myStrip(chs):
pass
def myLstrip(chs):
if len(chs) == 0:
return chs
chsList = []
chsList.extend(chs)
for i in range(len(chsList)):
if chsList[0] in whitespace:
chsList.pop(0)
else:
break
return ''.join(chsList)
def myRstrip(chs):
if len(chs) == 0:
return chs
chsList = []
chsList.extend(chs)
for i in range(len(chsList)):
if chsList[-1] in whitespace:
chsList.pop()
else:
break
return ''.join(chsList)
if __name__ == '__main__':
myStr = ' hello '
print '|' + myStr + '|'
# print '|' + myStrip[myStr] + '|'
print '|' + myLstrip(myStr) + '|'
print '|' + myRstrip(myStr) + '|'
创建一个整数到IP地址的转换程序,如下格式:WWW.XXX.YYY.ZZZ
如2130706433转换为127.0.0.1
#!/usr/bin/env python
def ip2int(ipaddr):
iplist = ipaddr.split('.')
result = 0
for i in range(4):
result += int(iplist[i]) * (256 ** (3 - i))
return result
def int2ip(num):
iplist = []
for i in range(3):
num, modnum = divmod(num, 256)
iplist.insert(0,str(modnum))
iplist.insert(0, str(num))
return '.'.join(iplist)
def test():
ip = raw_input('Input an ip address: ')
print ip2int(ip)
number = int(raw_input('Input a number: '))
print int2ip(number)
if __name__ == '__main__':
test()
一、字典的定义
>>> mydict = {'name' : 'tom', 'age' : 23}
>>> adict = {}
>>> bdict = {}.fromkeys(('x', 'y'), 10)
>>> bdict
{'y': 10, 'x': 10}
- 打印字典的每个键-值对:
>>> for eachKey in bdict:
... print '%s:%s' % (eachKey,bdict[eachKey])
...
y:10
x:10
>>> bdict
{'y': 10, 'x': 10}
更新字典
>>> mydict['name'] = bob
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bob' is not defined
>>> mydict['name'] = 'bob'
>>> mydict['email'] = 'bob@test.com'
>>> mydict
{'age': 23, 'name': 'bob', 'email': 'bob@test.com'}、
删除
>>> del mydict['age']
>>>
>>> mydict
{'name': 'bob', 'email': 'bob@test.com'}
>>> mydict.pop('name')
'bob'
>>> mydict
{'email': 'bob@test.com'}
>>> mydict.clear()
>>> mydict
{}
二、字典的方法:
>>> mydict = {'name' : 'bob', 'age' : 23}
>>> mydict
{'age': 23, 'name': 'bob'}
>>> mydict.keys() 返回键
['age', 'name']
>>> mydict.values() 返回值
[23, 'bob']
>>> mydict.items() 返回键-值对的元组列表
[('age', 23), ('name', 'bob')]
>>> adict = {'email' : 'tom@test.com', 'phone' : '123456'}
>>> mydict.update(adict) 把adict的内容,加入到mydict中
>>> mydict
{'phone': '123456', 'age': 23, 'name': 'bob', 'email': 'tom@test.com'}
>>> adict
{'phone': '123456', 'email': 'tom@test.com'}
三、字典练习
#!/usr/bin/env python
import getpass
db = {}
def newUser():
username = raw_input('username: ')
if username in db:
print " 33[32;1m%s alread exist! 33[0m" % username
else:
# password = raw_input('password: ')
password = getpass.getpass()
db[username] = password
def oldUser():
username = raw_input('username: ')
password = raw_input('password: ')
if username in db:
if db.get(username) == password:
print ' 33[32;1mlogin successful1 33[0m'
else:
print ' 33[32;1mlogin incorrect. 33[0m'
else:
print ' 33[32;1mlogin name is error. 33[0m'
CMDs = {'n' : newUser, 'o' : oldUser}
def showMenu():
prompt = '''(New) user
(Old) user
(Quit).
please input your choice: '''
while True:
choice = raw_input(prompt).strip()[0].lower()
if choice not in 'noq':
print ' 33[31;1merror : n/o/q ... 33[0m'
continue
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showMenu()
一、条件及语句
1、在python中没有case语句,可以使用if/elif,或者使用字典
#!/usr/bin/env python
db = { 'create' : 'aaaa', 'del' : 'bbbb', 'modify' : 'cccc'}
choice = raw_input('enter something:')
if db.get(choice):
print db[choice]
2、使用元组代替case
#!/usr/bin/env python
choice = raw_input('enter something:')
if choice in ('create', 'delete', 'update'):
action = '%s item' % choice
print action
3、三元运算符
>>> x = 8
>>> y = 5
>>> smaller = x if x < y else y
>>> smaller
5
迭代器
>>> i = iter(range(10))
>>> for j in i:
... print j
...
0
1
2
3
4
5
6
7
8
9
>>> i = iter(range(4))
>>> i.next()
0
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> a = xrange(3)
>>> print a
xrange(3)
>>> for i in a:
... print i
...
0
1
2
4、使用range计算阶乘
#!/usr/bin/env python
a = 1
num = int(raw_input('enter a number:'))
for i in range(1, num + 1):
a *= i
print a
5、使用递归函数计算阶乘
#!/usr/bin/env python
def cf(num):
if num == 1:
return 1
else:
return num * cf(num - 1)
if __name__ == '__main__':
print cf(5)
注意:
重要:
当一个日志文件很大,比如G单位,不要直接打开
f = file('new.log')
data = ( line for line in f)
data
data.next()
文件操作
1、以只读方式打开文件
f = file('/root/bin/pwd.py')
a = f.read() 将文件的全部内容读出来,成为一个大字符串,赋值给a
f.seek(0) 将文件指针移回到文件头部
b = f.readlinse() 将文件的全部内容读出来,成为一个列表,赋值给b
f.seek(0) 将文件指针称回到文件头部
c = f.readline() 读取文件和一行,赋值给c
f.seek(0, 0) 将文件指针称回到文件头部 第一个0为偏移量 第二个0相对位置 第二个值有0/1/2 0表示文件的开头 1表示当前位置 2表示文件结尾
f.tell() 查看当前指针在什么位置
for i in f:
print i, 因为第一行发问已经有驾车了,就不要让print再打印
练习:
读取一个文件,移除以#开头的行,将其打印在屏幕上
方法一:
#!/usr/bin/env python
import sys
def grep1(fname):
f = file(fname)
for i in f:
if i != ' ' and i.strip()[0] != '#':
print i,
f.close()
if __name__ == '__main__':
grep1(sys.argv[1])
方法二:
#!/usr/bin/env python
import sys
def grep1(fname):
f = file(fname)
for i in f:
if i[0] in '# ':
continue
else:
print i,
f.close()
if __name__ == '__main__':
grep1(sys.argv[1])
方法三:推荐
#!/usr/bin/env python
import sys
try:
f = open(sys.argv[1])
except IndexError:
print 'you must input a filename'
except IOError:
print 'no such file or file is a directory.'
else:
for i in f:
if (not i.startswith('#')) and i != ' ':
print i,
f.close()
方法四:
#!/usr/bin/env python
import sys
import os
def grep1(fname):
f = open(fname)
for i in f:
if(not i.startswith('#')) and i != ' ':
print i,
f.close()
if __name__ == '__main__':
grep1(sys.argv[1])