python-04


  1. >>> list('abcde')
  2. ['a', 'b', 'c', 'd', 'e']
  3. >>> list(('abc', 123))
  4. ['abc', 123]
  5. >>> str(['hello', 'world'])
  6. "['hello', 'world']"
  7. >>> tuple('abcde')
  8. ('a', 'b', 'c', 'd', 'e')
  9. >>> alist = [32,54,234,436,221]
  10. >>> for i, j in enumerate(alist):
  11. ... print '#%s: %s' % (i, j)
  12. ...
  13. #0: 32
  14. #1: 54
  15. #2: 234
  16. #3: 436
  17. #4: 221
  18. >>> max(alist)
  19. 436
  20. >>> min(alist)
  21. 32
  22. >>> len(alist)
  23. 5
  24. >>> for i in reversed(alist):
  25. ... print i,
  26. ...
  27. 221 436 234 54 32
  28. >>> sorted(alist)
  29. [32, 54, 221, 234, 436]
  30. >>> alist.reverse()
  31. >>> alist
  32. [221, 436, 234, 54, 32]
  33. >>> alist.sort()
  34. >>> alist
  35. [32, 54, 221, 234, 436]
  36. >>> zip ('abc', 'zxc')
  37. [('a', 'z'), ('b', 'x'), ('c', 'c')]
  38. >>> zip((1,2), ['abc', 'zxc'])
  39. [(1, 'abc'), (2, 'zxc')]

  1. #!/usr/bin/env python
  2. import string
  3. a = string.letters + '_'
  4. nums = string.digits
  5. print 'welcome to the...'
  6. print 'test must be at least 2 chars long.'
  7. b = raw_input('identifier to test? ')
  8. if len(b) > 1:
  9. if b[0] not in a:
  10. print 'first symbol must be alphabetic'
  11. else:
  12. for c in b[1:]:
  13. if c not in a + nums:
  14. print 'other symbol must be aphanumeric'
  15. break
  16. else:
  17. print 'OK as an identifier.'
格式化输出
  1. >>> print "%-8s%-15s%-12s" % ('name', 'email', 'moblie')
  2. name email moblie
  3. >>> print "%-8s%-15s%-12s" % ('tom', 'tom@qq.com', '1234567890123')
  4. tom tom@qq.com 1234567890123
  5. >>> print '%d' % 22
  6. 22
  7. >>> print '%5d' % 22
  8. 22
  9. >>> print '%05d' % 22
  10. 00022
  11. >>> print '%*s' % (10, 'tom')
  12. tom
  13. >>> print '%*s' % (20, 'tom')
  14. tom
  15. >>> print '%-10s' % 'tom'
  16. tom

  1. #!/usr/bin/env python
  2. width = 48
  3. data = []
  4. while True:
  5. a = raw_input('enter data . exit: ')
  6. if a == '.':
  7. break
  8. data.append(a)
  9. print '+' + '*' * width + '+'
  10. for i in data:
  11. b, c = divmod((width - len(i)), 2)
  12. print '+' + ' ' * b + i + ' ' * (b + c) + '+'
  13. print '+' + '*' * width + '+'
  1. #!/usr/bin/env python
  2. width = 48
  3. data = []
  4. while True:
  5. a = raw_input('enter data . exit: ')
  6. if a == '.':
  7. break
  8. data.append(a)
  9. print '+' + '*' * width + '+'
  10. for i in data:
  11. print '+' + i.center(width) + '+'
  12. print '+' + '*' * width + '+'

  1. >>> import string
  2. >>> a = string.Template('$name is $age years old.')
  3. >>> a.substitute(name = 'bob', age = 23)
  4. 'bob is 23 years old.'
  5. >>> a.substitute(name = 'tom', age = 20)
  6. 'tom is 20 years old.'
  7. >>> import os
  8. >>> os.system('ls /root/')
编写一个python脚本,添加一个用户,随机密码8位,并发送邮件给管理员
  1. #!/usr/bin/env python
  2. import string
  3. import random
  4. import os
  5. allChs = string.letters + string.digits
  6. a ="""your account is created.
  7. username: $user
  8. password: $pwd"""
  9. def genPwd(num = 8):
  10. pwd = ''
  11. for i in range(num):
  12. pwd += random.choice(allChs)
  13. return pwd
  14. if __name__ == '__main__':
  15. username = raw_input('username: ')
  16. password = genPwd()
  17. os.system('useradd %s' % username)
  18. os.system('echo %s | passwd --stdin %s' % (password,username))
  19. b = string.Template(a)
  20. os.system("echo '%s' |mail -s 'create user' root" % b.substitute(user = username, pwd = password))


  1. >>> 'hello tom'.capitalize()        //将首字母大写
  2. 'Hello tom'
  3. >>> 'hello tom'.center(20)        //设置居中
  4. ' hello tom '
  5. >>> 'hello tom'.count('o')        //统计字母o出现的次数
  6. 2
  7. >>> 'hello tom'.count('o',5)
  8. 1
  9. >>> 'hello tom'.count('o', 0, 5)
  10. 1
  11. >>> 'hello tom'.endswith('tom')        //检查字符串是否以tom作为结尾True
  12. True
  13. >>> 'hello tom'.startswith('hello')
  14. True
  15. >>> 'hello tom'.find('ll')        //查找ll出现的位置下标,找不到返回-1
  16. 2
  17. >>> filename = ['hello', 'txt']
  18. >>> '.'.join(filename)
  19. 'hello.txt'
  20. >>> ' hello '.strip()        //去掉字符串两端的空白
  21. 'hello'

  1. >>> alist = []
  2. >>> alist.append('hello')
  3. >>> alist.append('hello')
  4. >>> alist.append('bob')
  5. >>> alist.count('hello')
  6. 2
  7. >>> alist
  8. ['hello', 'hello', 'bob']
  9. >>> alist.extend('new')
  10. >>> alist
  11. ['hello', 'hello', 'bob', 'n', 'e', 'w']
  12. >>> alist.extend(['new', 'line'])
  13. >>> alist
  14. ['hello', 'hello', 'bob', 'n', 'e', 'w', 'new', 'line']
  15. >>> alist.insert(1, 'abc')
  16. >>> alist
  17. ['hello', 'abc', 'hello', 'bob', 'n', 'e', 'w', 'new', 'line']
  18. >>> alist.pop()
  19. 'line'
  20. >>> alist
  21. ['hello', 'abc', 'hello', 'bob', 'n', 'e', 'w', 'new']
  22. >>> alist.pop(2)
  23. 'hello'
  24. >>> alist
  25. ['hello', 'abc', 'bob', 'n', 'e', 'w', 'new']
  26. >>> alist.remove('w')
  27. >>> alist
  28. ['hello', 'abc', 'bob', 'n', 'e', 'new']
  29. >>> alist.reverse()
  30. >>> alist
  31. ['new', 'e', 'n', 'bob', 'abc', 'hello']
  32. >>> alist.sort()
  33. >>> alist
  34. ['abc', 'bob', 'e', 'hello', 'n', 'new']
  35. >>>
使用列表模拟栈结构
  1. #!/usr/bin/env python
  2. stack = []
  3. def pushit():
  4. item = raw_input('enter item: ')
  5. stack.append(item)
  6. def popit():
  7. if len(stack) == 0:
  8. print 'Empty stack'
  9. else:
  10. print 'pop', stack.pop(), 'from stack'
  11. def viewstack():
  12. print stack
  13. CMDs = {'p': pushit, 'o': popit, 'v': viewstack}
  14. def showmenu():
  15. prompt = '''(P)ush
  16. p()p
  17. (V)iew
  18. (Q)uit
  19. please make a choice: '''
  20. while True:
  21. try:
  22. choice = raw_input(prompt).strip()[0].lower()
  23. except (KeyboardInterrupt, EOFError, IndexError):
  24. choice = 'q'
  25. if choice not in 'povq':
  26. continue
  27. if choice == 'q':
  28. break
  29. CMDs[choice]()
  30. if __name__ == '__main__':
  31. showmenu()
  1. >>> alist = ['age', 123]
  2. >>> blist = alist
  3. >>> blist[1] = 23    //注意,改变blist[1],alist[1]也会相应的被修改
  4. >>> blist
  5. ['age', 23]
  6. >>> alist            
  7. ['age', 23]
  8. >>> alist = ['age', 123]
  9. >>> blist = alist[:]
  10. >>> blist[1] = 23        //修改了blist[1],alist[1]并不会被修改
  11. >>> alist
  12. ['age', 123]
  13. >>> blist
  14. ['age', 23]
  15. >>> import copy
  16. >>> alist = ['age', 123]
  17. >>> blist = copy.copy(alist)
  18. >>> blist
  19. ['age', 123]
  20. >>> blist[1] = 25    //copy.copy实现了深拷贝,修改blist[1],不会修改alist[1]
  21. >>> blist
  22. ['age', 25]
  23. >>> alist
  24. ['age', 123]





posted @ 2016-12-19 14:22  Final233  阅读(274)  评论(0编辑  收藏  举报