zoukankan      html  css  js  c++  java
  • python-05

    去除空格
    方法一:使用字符串
    1. #!/usr/bin/env python
    2. whitespace = ' vf'
    3. def myStrip(chs):
    4. pass
    5. def myLstrip(chs):
    6. if len(chs) ==0:
    7. return chs
    8. strlen = len(chs)
    9. for i in range(strlen):
    10. if chs[i] not in whitespace:
    11. break
    12. else:
    13. return ''
    14. return chs[i:]
    15. def myRstrip(chs):
    16. if len(chs) == 0:
    17. return chs
    18. strlen =len(chs)
    19. for i in range(-1, -(strlen + 1), -1):
    20. if chs[i] not in whitespace:
    21. break
    22. else:
    23. return ''
    24. return chs[:i + 1]
    25. if __name__ == '__main__':
    26. myStr = ' hello '
    27. print '|' + myStr + '|'
    28. # print '|' + myStrip[myStr] + '|'
    29. print '|' + myLstrip(myStr) + '|'
    30. print '|' + myRstrip(myStr) + '|'
    方法二:使用列表
    1. #!/usr/bin/env python
    2. whitespace = ' vf'
    3. def myStrip(chs):
    4. pass
    5. def myLstrip(chs):
    6. if len(chs) == 0:
    7. return chs
    8. chsList = []
    9. chsList.extend(chs)
    10. for i in range(len(chsList)):
    11. if chsList[0] in whitespace:
    12. chsList.pop(0)
    13. else:
    14. break
    15. return ''.join(chsList)
    16. def myRstrip(chs):
    17. if len(chs) == 0:
    18. return chs
    19. chsList = []
    20. chsList.extend(chs)
    21. for i in range(len(chsList)):
    22. if chsList[-1] in whitespace:
    23. chsList.pop()
    24. else:
    25. break
    26. return ''.join(chsList)
    27. if __name__ == '__main__':
    28. myStr = ' hello '
    29. print '|' + myStr + '|'
    30. # print '|' + myStrip[myStr] + '|'
    31. print '|' + myLstrip(myStr) + '|'
    32. print '|' + myRstrip(myStr) + '|'
    创建一个整数到IP地址的转换程序,如下格式:WWW.XXX.YYY.ZZZ
    如2130706433转换为127.0.0.1
    1. #!/usr/bin/env python
    2. def ip2int(ipaddr):
    3. iplist = ipaddr.split('.')
    4. result = 0
    5. for i in range(4):
    6. result += int(iplist[i]) * (256 ** (3 - i))
    7. return result
    8. def int2ip(num):
    9. iplist = []
    10. for i in range(3):
    11. num, modnum = divmod(num, 256)
    12. iplist.insert(0,str(modnum))
    13. iplist.insert(0, str(num))
    14. return '.'.join(iplist)
    15. def test():
    16. ip = raw_input('Input an ip address: ')
    17. print ip2int(ip)
    18. number = int(raw_input('Input a number: '))
    19. print int2ip(number)
    20. if __name__ == '__main__':
    21. test()
    一、字典的定义
    1. >>> mydict = {'name' : 'tom', 'age' : 23}
    2. >>> adict = {}
    3. >>> bdict = {}.fromkeys(('x', 'y'), 10)
    4. >>> bdict
    5. {'y': 10, 'x': 10}
    6. 打印字典的每个键-值对:
    7. >>> for eachKey in bdict:
    8. ... print '%s:%s' % (eachKey,bdict[eachKey])
    9. ...
    10. y:10
    11. x:10
    12. >>> bdict
    13. {'y': 10, 'x': 10}
    14. 更新字典
    15. >>> mydict['name'] = bob
    16. Traceback (most recent call last):
    17. File "<stdin>", line 1, in <module>
    18. NameError: name 'bob' is not defined
    19. >>> mydict['name'] = 'bob'
    20. >>> mydict['email'] = 'bob@test.com'
    21. >>> mydict
    22. {'age': 23, 'name': 'bob', 'email': 'bob@test.com'}、
    23. 删除
    24. >>> del mydict['age']
    25. >>>
    26. >>> mydict
    27. {'name': 'bob', 'email': 'bob@test.com'}
    28. >>> mydict.pop('name')
    29. 'bob'
    30. >>> mydict
    31. {'email': 'bob@test.com'}
    32. >>> mydict.clear()
    33. >>> mydict
    34. {}
    二、字典的方法:
    1. >>> mydict = {'name' : 'bob', 'age' : 23}
    2. >>> mydict
    3. {'age': 23, 'name': 'bob'}
    4. >>> mydict.keys()        返回键
    5. ['age', 'name']
    6. >>> mydict.values()        返回值
    7. [23, 'bob']
    8. >>> mydict.items()        返回键-值对的元组列表
    9. [('age', 23), ('name', 'bob')]
    10. >>> adict = {'email' : 'tom@test.com', 'phone' : '123456'}
    11. >>> mydict.update(adict)        把adict的内容,加入到mydict中
    12. >>> mydict
    13. {'phone': '123456', 'age': 23, 'name': 'bob', 'email': 'tom@test.com'}
    14. >>> adict
    15. {'phone': '123456', 'email': 'tom@test.com'}
    三、字典练习
    1. #!/usr/bin/env python
    2. import getpass
    3. db = {}
    4. def newUser():
    5. username = raw_input('username: ')
    6. if username in db:
    7. print "33[32;1m%s alread exist!33[0m" % username
    8. else:
    9. # password = raw_input('password: ')
    10. password = getpass.getpass()
    11. db[username] = password
    12. def oldUser():
    13. username = raw_input('username: ')
    14. password = raw_input('password: ')
    15. if username in db:
    16. if db.get(username) == password:
    17. print '33[32;1mlogin successful133[0m'
    18. else:
    19. print '33[32;1mlogin incorrect.33[0m'
    20. else:
    21. print '33[32;1mlogin name is error.33[0m'
    22. CMDs = {'n' : newUser, 'o' : oldUser}
    23. def showMenu():
    24. prompt = '''(New) user
    25. (Old) user
    26. (Quit).
    27. please input your choice: '''
    28. while True:
    29. choice = raw_input(prompt).strip()[0].lower()
    30. if choice not in 'noq':
    31. print '33[31;1merror : n/o/q ...33[0m'
    32. continue
    33. if choice == 'q':
    34. break
    35. CMDs[choice]()
    36. if __name__ == '__main__':
    37. showMenu()

    一、条件及语句
    1、在python中没有case语句,可以使用if/elif,或者使用字典
    1. #!/usr/bin/env python
    2. db = { 'create' : 'aaaa', 'del' : 'bbbb', 'modify' : 'cccc'}
    3. choice = raw_input('enter something:')
    4. if db.get(choice):
    5. print db[choice]
    2、使用元组代替case
    1. #!/usr/bin/env python
    2. choice = raw_input('enter something:')
    3. if choice in ('create', 'delete', 'update'):
    4. action = '%s item' % choice
    5. print action
    3、三元运算符
    1. >>> x = 8
    2. >>> y = 5
    3. >>> smaller = x if x < y else y
    4. >>> smaller
    5. 5
    迭代器
    1. >>> i = iter(range(10))
    2. >>> for j in i:
    3. ... print j
    4. ...
    5. 0
    6. 1
    7. 2
    8. 3
    9. 4
    10. 5
    11. 6
    12. 7
    13. 8
    14. 9
    15. >>> i = iter(range(4))
    16. >>> i.next()
    17. 0
    18. >>> i.next()
    19. 1
    20. >>> i.next()
    21. 2
    22. >>> i.next()
    23. 3
    24. >>> i.next()
    25. Traceback (most recent call last):
    26. File "<stdin>", line 1, in <module>
    27. StopIteration
    28. >>> a = xrange(3)
    29. >>> print a
    30. xrange(3)
    31. >>> for i in a:
    32. ... print i
    33. ...
    34. 0
    35. 1
    36. 2
    4、使用range计算阶乘
    1. #!/usr/bin/env python
    2. a = 1
    3. num = int(raw_input('enter a number:'))
    4. for i in range(1, num + 1):
    5. a *= i
    6. print a
    5、使用递归函数计算阶乘
    1. #!/usr/bin/env python
    2. def cf(num):
    3. if num == 1:
    4. return 1
    5. else:
    6. return num * cf(num - 1)
    7. if __name__ == '__main__':
    8. print cf(5)
    注意:
    重要:
    当一个日志文件很大,比如G单位,不要直接打开
    f = file('new.log')
    data = ( line for line in f)
    data 
    data.next()

    文件操作
    1、以只读方式打开文件
    1. f = file('/root/bin/pwd.py')
    2. a = f.read() 将文件的全部内容读出来,成为一个大字符串,赋值给a
    3. f.seek(0) 将文件指针移回到文件头部
    4. b = f.readlinse() 将文件的全部内容读出来,成为一个列表,赋值给b
    5. f.seek(0) 将文件指针称回到文件头部
    6. c = f.readline() 读取文件和一行,赋值给c
    7. f.seek(0, 0) 将文件指针称回到文件头部 第一个0为偏移量 第二个0相对位置 第二个值有0/1/2 0表示文件的开头 1表示当前位置 2表示文件结尾
    8. f.tell() 查看当前指针在什么位置
    9. for i in f:
    10. print i, 因为第一行发问已经有驾车了,就不要让print再打印


    练习:
    读取一个文件,移除以#开头的行,将其打印在屏幕上
    方法一:
    1. #!/usr/bin/env python
    2. import sys
    3. def grep1(fname):
    4. f = file(fname)
    5. for i in f:
    6. if i != ' ' and i.strip()[0] != '#':
    7. print i,
    8. f.close()
    9. if __name__ == '__main__':
    10. grep1(sys.argv[1])
    方法二:
    1. #!/usr/bin/env python
    2. import sys
    3. def grep1(fname):
    4. f = file(fname)
    5. for i in f:
    6. if i[0] in '# ':
    7. continue
    8. else:
    9. print i,
    10. f.close()
    11. if __name__ == '__main__':
    12. grep1(sys.argv[1])
    方法三:推荐
    1. #!/usr/bin/env python
    2. import sys
    3. try:
    4. f = open(sys.argv[1])
    5. except IndexError:
    6. print 'you must input a filename'
    7. except IOError:
    8. print 'no such file or file is a directory.'
    9. else:
    10. for i in f:
    11. if (not i.startswith('#')) and i != ' ':
    12. print i,
    13. f.close()
    方法四:
    1. #!/usr/bin/env python
    2. import sys
    3. import os
    4. def grep1(fname):
    5. f = open(fname)
    6. for i in f:
    7. if(not i.startswith('#')) and i != ' ':
    8. print i,
    9. f.close()
    10. if __name__ == '__main__':
    11. grep1(sys.argv[1])





  • 相关阅读:
    Element + 列表增删改查
    int 型动态数组
    Vue.prototype.$ 和 Vue.use()
    Vue.js生成一个Vue实例
    Element 树形组件
    使用Vuex 实现标签数字增加与减小
    使用指针做形参
    JavaWeb学习之HttpServletRequest
    JavaWeb学习之HttpServletResponse
    JavaWeb学习之Javaweb核心servlet
  • 原文地址:https://www.cnblogs.com/fina/p/6197341.html
Copyright © 2011-2022 走看看