python-04
>>> list('abcde')
['a', 'b', 'c', 'd', 'e']
>>> list(('abc', 123))
['abc', 123]
>>> str(['hello', 'world'])
"['hello', 'world']"
>>> tuple('abcde')
('a', 'b', 'c', 'd', 'e')
>>> alist = [32,54,234,436,221]
>>> for i, j in enumerate(alist):
... print '#%s: %s' % (i, j)
...
#0: 32
#1: 54
#2: 234
#3: 436
#4: 221
>>> max(alist)
436
>>> min(alist)
32
>>> len(alist)
5
>>> for i in reversed(alist):
... print i,
...
221 436 234 54 32
>>> sorted(alist)
[32, 54, 221, 234, 436]
>>> alist.reverse()
>>> alist
[221, 436, 234, 54, 32]
>>> alist.sort()
>>> alist
[32, 54, 221, 234, 436]
>>> zip ('abc', 'zxc')
[('a', 'z'), ('b', 'x'), ('c', 'c')]
>>> zip((1,2), ['abc', 'zxc'])
[(1, 'abc'), (2, 'zxc')]
#!/usr/bin/env python
import string
a = string.letters + '_'
nums = string.digits
print 'welcome to the...'
print 'test must be at least 2 chars long.'
b = raw_input('identifier to test? ')
if len(b) > 1:
if b[0] not in a:
print 'first symbol must be alphabetic'
else:
for c in b[1:]:
if c not in a + nums:
print 'other symbol must be aphanumeric'
break
else:
print 'OK as an identifier.'
格式化输出
>>> print "%-8s%-15s%-12s" % ('name', 'email', 'moblie')
name email moblie
>>> print "%-8s%-15s%-12s" % ('tom', 'tom@qq.com', '1234567890123')
tom tom@qq.com 1234567890123
>>> print '%d' % 22
22
>>> print '%5d' % 22
22
>>> print '%05d' % 22
00022
>>> print '%*s' % (10, 'tom')
tom
>>> print '%*s' % (20, 'tom')
tom
>>> print '%-10s' % 'tom'
tom
#!/usr/bin/env python
width = 48
data = []
while True:
a = raw_input('enter data . exit: ')
if a == '.':
break
data.append(a)
print '+' + '*' * width + '+'
for i in data:
b, c = divmod((width - len(i)), 2)
print '+' + ' ' * b + i + ' ' * (b + c) + '+'
print '+' + '*' * width + '+'
改
#!/usr/bin/env python
width = 48
data = []
while True:
a = raw_input('enter data . exit: ')
if a == '.':
break
data.append(a)
print '+' + '*' * width + '+'
for i in data:
print '+' + i.center(width) + '+'
print '+' + '*' * width + '+'
>>> import string
>>> a = string.Template('$name is $age years old.')
>>> a.substitute(name = 'bob', age = 23)
'bob is 23 years old.'
>>> a.substitute(name = 'tom', age = 20)
'tom is 20 years old.'
>>> import os
>>> os.system('ls /root/')
编写一个python脚本,添加一个用户,随机密码8位,并发送邮件给管理员
#!/usr/bin/env python
import string
import random
import os
allChs = string.letters + string.digits
a ="""your account is created.
username: $user
password: $pwd"""
def genPwd(num = 8):
pwd = ''
for i in range(num):
pwd += random.choice(allChs)
return pwd
if __name__ == '__main__':
username = raw_input('username: ')
password = genPwd()
os.system('useradd %s' % username)
os.system('echo %s | passwd --stdin %s' % (password,username))
b = string.Template(a)
os.system("echo '%s' |mail -s 'create user' root" % b.substitute(user = username, pwd = password))
>>> 'hello tom'.capitalize() //将首字母大写
'Hello tom'
>>> 'hello tom'.center(20) //设置居中
' hello tom '
>>> 'hello tom'.count('o') //统计字母o出现的次数
2
>>> 'hello tom'.count('o',5)
1
>>> 'hello tom'.count('o', 0, 5)
1
>>> 'hello tom'.endswith('tom') //检查字符串是否以tom作为结尾True
True
>>> 'hello tom'.startswith('hello')
True
>>> 'hello tom'.find('ll') //查找ll出现的位置下标,找不到返回-1
2
>>> filename = ['hello', 'txt']
>>> '.'.join(filename)
'hello.txt'
>>> ' hello '.strip() //去掉字符串两端的空白
'hello'
>>> alist = []
>>> alist.append('hello')
>>> alist.append('hello')
>>> alist.append('bob')
>>> alist.count('hello')
2
>>> alist
['hello', 'hello', 'bob']
>>> alist.extend('new')
>>> alist
['hello', 'hello', 'bob', 'n', 'e', 'w']
>>> alist.extend(['new', 'line'])
>>> alist
['hello', 'hello', 'bob', 'n', 'e', 'w', 'new', 'line']
>>> alist.insert(1, 'abc')
>>> alist
['hello', 'abc', 'hello', 'bob', 'n', 'e', 'w', 'new', 'line']
>>> alist.pop()
'line'
>>> alist
['hello', 'abc', 'hello', 'bob', 'n', 'e', 'w', 'new']
>>> alist.pop(2)
'hello'
>>> alist
['hello', 'abc', 'bob', 'n', 'e', 'w', 'new']
>>> alist.remove('w')
>>> alist
['hello', 'abc', 'bob', 'n', 'e', 'new']
>>> alist.reverse()
>>> alist
['new', 'e', 'n', 'bob', 'abc', 'hello']
>>> alist.sort()
>>> alist
['abc', 'bob', 'e', 'hello', 'n', 'new']
>>>
使用列表模拟栈结构
#!/usr/bin/env python
stack = []
def pushit():
item = raw_input('enter item: ')
stack.append(item)
def popit():
if len(stack) == 0:
print 'Empty stack'
else:
print 'pop', stack.pop(), 'from stack'
def viewstack():
print stack
CMDs = {'p': pushit, 'o': popit, 'v': viewstack}
def showmenu():
prompt = '''(P)ush
p()p
(V)iew
(Q)uit
please make a choice: '''
while True:
try:
choice = raw_input(prompt).strip()[0].lower()
except (KeyboardInterrupt, EOFError, IndexError):
choice = 'q'
if choice not in 'povq':
continue
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()
>>> alist = ['age', 123]
>>> blist = alist
>>> blist[1] = 23
//注意,改变blist[1],alist[1]也会相应的被修改>>> blist
['age', 23]
>>> alist
['age', 23]
>>> alist = ['age', 123]
>>> blist = alist[:]
>>> blist[1] = 23 //修改了blist[1],alist[1]并不会被修改
>>> alist
['age', 123]
>>> blist
['age', 23]
>>> import copy
>>> alist = ['age', 123]
>>> blist = copy.copy(alist)
>>> blist
['age', 123]
>>> blist[1] = 25 //copy.copy实现了深拷贝,修改blist[1],不会修改alist[1]
>>> blist
['age', 25]
>>> alist
['age', 123]