sunren 发表于 2018-8-10 12:15:51

python基础2

  python基础2
  ####转义符号####
  一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符
  \n: 代表换行符 \": 代表双引号本身
  \t: 代表tab符 \': 代表单引号本身
  In : print 'let's go'      ###要将's转义###
  File "<ipython-input-1-1f59d2736eda>", line 1
  print 'let's go'
  ^
  SyntaxError: invalid syntax
  In : print 'let\'s go'
  let's go
  ###字符串定义####
  1 单引号
  In : str1 = "hello"
  In : type(str1)
  Out: str
  2 双引号
  In : srt2 = 'hello'
  In : type(srt2)
  Out: str
  3 三个双引号
  In : str3 = """hello"""
  In : type(str3)
  Out: str
  ###字符串切片###
  >>> s = 'hello'
  >>> s
  'llo'
  >>> s
  'hello'
  >>> s
  'lo'
  >>> s[:3]
  'hel'
  >>> s
  'hl'
  >>>
  如果只有[:],则表示全部
  ####字符串常用操作####
  In : s = 'hello'
  In : type(s)
  Out: str
  In : s.
  s.capitalizes.format      s.isupper   s.rindex      s.strip
  s.center      s.index       s.join      s.rjust       s.swapcase
  s.count       s.isalnum   s.ljust       s.rpartitions.title
  s.decode      s.isalpha   s.lower       s.rsplit      s.translate
  s.encode      s.isdigit   s.lstrip      s.rstrip      s.upper
  s.endswith    s.islower   s.partition   s.split       s.zfill
  s.expandtabss.isspace   s.replace   s.splitlines
  s.find      s.istitle   s.rfind       s.startswith
  In : s.capitalize()      ###将第一个转换成大写字母###
  Out: 'Hello'
  In : help (s.capitalize)    ###查看帮助,按q退出###
  In : help(s.c)
  s.capitalizes.center      s.count
  In : help(s.center)      ###给一个宽度,如果字符串小于该宽度,就会自动填充,默认使用空格,如果传递的参数,除了数字还有字符,则会使用该字符填充,返回值为srt
  例:
  In : s.center(10,'#')
  Out: '##hello###'
  In : s.center(10)
  Out: 'hello   '
  In :
  In : s.
  s.capitalizes.format      s.isupper   s.rindex      s.strip
  s.center      s.index       s.join      s.rjust       s.swapcase
  s.count       s.isalnum   s.ljust       s.rpartitions.title
  s.decode      s.isalpha   s.lower       s.rsplit      s.translate
  s.encode      s.isdigit   s.lstrip      s.rstrip      s.upper
  s.endswith    s.islower   s.partition   s.split       s.zfill
  s.expandtabss.isspace   s.replace   s.splitlines
  s.find      s.istitle   s.rfind       s.startswith
  In : "WORD".isupper()    ###判断是否为大写,返回值为bool类型
  Out: True
  In : "2l".isalnum()      ###数字和字母###
  Out: True            ###返回bool值为true####
  In : "2l-".isalnum()
  Out: False
  In : "Wojfh".isalpha()    ###字母###
  Out: True
  In : "234".isdigit()    ###数字###
  Out: True
  In : "ldsjfkai".islower()    ###小写字母###
  Out: True
  In : "   ".isspace()    ###空格###
  Out: True
  In : "d ".isspace()
  Out: False
  In : "Heloo".istitle()    ###开头为大子字母###
  Out: True
  In : help(s.isupper)    ###查看帮助###
  Help on built-in function isupper:
  In :isupper(...)
  S.isupper() -> bool
  Return True if all cased characters in S are uppercase and there is
  at least one cased character in S, False otherwise.
  (END)
  ####导入模块srting###
  srting.digits
  string.letters
  In : import string
  In : string.digits
  Out: '0123456789'
  In : string.letters
  Out: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  编写程序:判断输入的字符串是否符合变量的规则
  程序1:
  import string
  print "欢迎进入变量名检测系统".center(50,'*')
  letter = raw_input("please input letters:")
  if letter in string.letters + '_':
  n = 1
  for letter1 in letter:
  if letter1 in string.letters + string.digits + "_":
  n +=1
  if n == len(letter):
  print "输入合法"
  else:
  print "输入的变量不合法"
  else:
  print "变量的第一个字符只能是字母或者下划线"
  执行结果:
  /usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/1.py
  ********欢迎进入变量名检测系统*********
  please input letters:sfak
  输入合法
  Process finished with exit code 0
  /usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/1.py
  please input letters:5kdgl
  变量的第一个字符只能是字母或者下划线
  Process finished with exit code 0
  程序2:
  import string
  alphas = string.letters
  nums = string.digits
  print "欢迎进入变量检测系统V1.0".center(50,"*")
  print 'Test string must be at least 1 char long'
  variable = raw_input("输入检测的变量名:")
  if len(variable) > 0:
  if variable not in alphas:
  print '变量名必须为字母或下划线开头'
  else:
  for ochar in variable:
  if ochar not in alphas + nums:
  print '无效的变量名'
  exit(1)
  print '%s 变量名合法' % variable
  else:
  print '变量名长度必须大于0'
  ###字符串的常用操作###
  In : s = " hello   "
  In : s.strip()    ###屏蔽前后的空格###
  Out: 'hello'
  In : s.lstrip()    ###屏蔽左边的空格###
  Out: 'hello   '
  In : s.rstrip()    ###屏蔽右边的空格###
  Out: ' hello'
  In : s = "hello"   ###中间的空格不能屏蔽###
  In : s.strip()
  Out: 'hello'
  In : ip = "172.25.254.12"
  In : ip.split('.')      ###指定分隔符为".",默认为空格,返回的是一个列表###
  Out: ['172', '25', '254', '12']
  In : "user1:x:1001:1001::/home/user1:/bin/bash".split(":")
  Out: ['user1', 'x', '1001', '1001', '', '/home/user1', '/bin/bash']
  In : "user1:x:1001:1001::/home/user1:/bin/bash".endswith("bash")    ###以bash结尾###
  Out: True
  In : "user1:x:1001:1001::/home/user1:/bin/bash".startswith("user1")    ###以user1开头###
  Out: True
  In : s.lower()    ###转换成小写字母###
  Out: 'hello'
  In : s.upper()    ###转换成大写字母###
  Out: 'HELLO'
  In : s = 'hElO'
  In : s.swapcase()    ###将大写转换成小写,小写转换成大写###
  Out: 'HeLo'
  练习:要求用户输入一个英文句子,统计该英文句子中含有单词的数目
  测试:输入:i like python very much
  输出:5
  a = raw_input("请输入一个英文句子:")
  lengthen = len(a.split())    ###字符串计算长度:len()可以计算长度###
  print lengthen
  测试:
  请输入一个英文句子:i like python very much
  5
  ###字符串的重复,连接,计算长度###
  In : print "===="*10
  ========================================
  In : print "hello"+"work=ld"
  hellowork=ld
  In : s = 'hello world'
  In : len(s)
  Out: 11
  ###字符串的常用操作###
  In : s
  Out: 'hello world'
  In : s.find('o')      ###判断'o'是否在str中,存在返回第一个出现的索引值,不存在返回-1.
  Out: 4
  In : s.find('p')
  Out: -1
  In : s.index('e')
  Out: 1
  In : s.index('o')      ###判断是否在str中,存在返回索引值,不存在就报错时抛出ValueError异常###
  Out: 4
  In : s.index('p')
  ---------------------------------------------------------------------------
  ValueError                              Traceback (most recent call last)
  <ipython-input-98-e5567af6b163> in <module>()
  ----> 1 s.index('p')
  ValueError: substring not found
  In :
  In : s
  Out: '#####'
  In : s.join("hello world")      ###以str作为分隔符,将序列“hello world”中的所有元素合并为一个新的字符串###
  Out: 'h#####e#####l#####l#####o##### #####w#####o#####r#####l#####d'
  ######str.replace(old,new[,count])
  - 将str中的old字符串替换为new字符串,并将替换后的新字符串返回,如果count指定,则只替换前count个字符串######
  In : s = "westos"
  In : s = "westos linux"
  In : s.replace("wes","HAHAHA")
  Out: 'HAHAHAtos linux'
  In : S = "WWWWestos linux"
  In : S.replace("W","HE",3)
  Out: 'HEHEHEWestos linux'
  #####列表#####
  列表中的元素可以是任意类型,列表,字符串均可
  In : li = []    ###定义一个空列表###
  In : type(li)
  Out: list
  In : li = ["fentiao",5, "male"]    ###列表中的元素可以是任意类型,列表,字符串,数字均可
  ####列表的索引与切片###
  In : li      ###索引###
  Out: 5
  In : li
  Out: 'fentiao'
  In : li
  Out: 'male'
  In : li      ###切片###
  Out: ['fentiao', 5]
  In : li[:]            ###全部###
  Out: ['fentiao', 5, 'male']
  In : li
  Out: ['fentiao', 5, 'male']
  In : len(li)      ###查看几个元素###
  Out: 3
  In : "fentiao" in li    ###查看fentiao是否在li列表中###
  Out: True
  In : "fendai" in li
  Out: False
  In : li1 = +    ###连接两个列表###
  In : print li1
  
  In : li3 = li*3      ###重复三次###
  In : print li3
  ['fentiao', 5, 'male', 'fentiao', 5, 'male', 'fentiao', 5, 'male']
  In : li = ['fentiao',7,'male',['westos','redhat','linux']]    ###列表中可以在嵌套列表###
  In : li    ###查询列表中的列表的元素##
  Out: 'linux'
  In : li
  Out: ['westos', 'redhat', 'linux']
  In : li.
  li.append   li.extend   li.insert   li.remove   li.sort
  li.count    li.index    li.pop      li.reverse
  In : li.append("hello")    ###在列表中添加hello,默认添加在末尾###
  In : print li
  ['fentiao', 7, 'male', ['westos', 'redhat', 'linux'], 'hello']
  In : li.insert(0,'hel')    ###在索引0前添加hel###
  In : print li
  ['hel', 'fentiao', 7, 'male', ['westos', 'redhat', 'linux'], 'hello']
  In : li.
  li.append   li.extend   li.insert   li.remove   li.sort
  li.count    li.index    li.pop      li.reverse
  In : help(li.extend)
  In :
  In : li.extend('hel')    ###添加多个元素###
  In : li
  Out:
  ['hel',
  'fentiao',
  7,
  'male',
  ['westos', 'redhat', 'linux'],
  'hello',
  'h',
  'e',
  'l']
  In : li = ['hwllo',2,3,'hao']
  In : li
  Out: ['hwllo', 2, 3, 'hao']
  In : li.extend(['hello','world'])    ###将hello,world,添加到列表中###
  In : li
  Out: ['hwllo', 2, 3, 'hao', 'hello', 'world']
  In : li
  Out: 'hwllo'
  In : li = 'fentiao'    ###列表中的元素是可变的,因此可修改列表中的元素,直接赋值,###
  In : li
  Out: ['fentiao', 2, 3, 'hao', 'hello', 'world']
  In : li.count('hao')    ###统计hao出现的次数###
  Out: 1
  In : li.count('fentiao')
  Out: 1
  In : li.count('fendai')
  Out: 0
  In : li.insert(2,'hello')
  In : li
  Out: ['fentiao', 2, 'hello', 3, 'hao', 'hello', 'world']
  In : li.count('hello')
  Out: 2
  In : li.index('fentiao')      ###查看fentiao的索引###
  Out: 0
  In : li.index(2)
  Out: 1
  In : li.index('hello')
  Out: 2
  In : li.re
  li.remove   li.reverse
  In : li.remove("hello")      ###删除hello###
  In : li
  Out: ['fentiao', 2, 3, 'hao', 'hello', 'world']
  In : li.remove(li)    ###删除li对应的元素###
  In : li
  Out: ['fentiao', 2, 3, 'hello', 'world']
  In : li.pop()      ###弹出,默认弹出最后一个###
  Out: 'world'
  In : li.pop(3)      ###弹出索引为3的元素###
  Out: 'hello'
  In : li
  Out: ['fentiao', 2, 3]
  In : li.pop()
  Out: 3
  In : li.pop()
  Out: 2
  In : li.pop()
  Out: 'fentiao'
  In : li
  Out: []
  In : li.pop()
  ---------------------------------------------------------------------------
  IndexError                              Traceback (most recent call last)
  <ipython-input-125-bdc59cbfe7c0> in <module>()
  ----> 1 li.pop()
  IndexError: pop from empty list
  In : del li    ###删除列表###
  In : li
  ---------------------------------------------------------------------------
  NameError                                 Traceback (most recent call last)
  <ipython-input-127-5ce4e85ef0aa> in <module>()
  ----> 1 li
  NameError: name 'li' is not defined
  In :
  练习:编写程序实现stack
  #!/usr/bin/env python
  #coding:utf-8
  li = []
  print "welcome to stack manage".center(50,'*')
  Format = '''
  please input:
  p(U)sh
  p(O)p
  (V)iew
  (Q)uit
  '''
  print Format
  while True:
  opera = raw_input("your choice:")
  if opera == "U":
  letter = raw_input("new item:")
  li.append(letter)
  print li
  elif opera == "O":
  if len(li)== 0:
  print "stack is empty"
  else:
  li.pop()
  print li
  elif opera == "V":
  if len(li) == 0:
  print "stack is empty"
  else:
  print li
  elif opera == "Q":
  print "quit stack manage".center(50,"*")
  exit(0)
  else:
  print "input u,o,v,q"
  执行结果:
  /usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/3.py
  *************welcome to stack manage**************
  please input:
  p(U)sh
  p(O)p
  (V)iew
  (Q)uit
  your choice:O
  stack is empty
  your choice:U
  new item:ksjdfl
  ['ksjdfl']
  your choice:V
  ['ksjdfl']
  your choice:Q
  ****************quit stack manage*****************
  Process finished with exit code 0
  ###练习###
  打印1-100中所有的偶数
  打印1-100中所有的奇数
  In : range(10)
  Out:
  In : range(1,10)
  Out:
  In : range(1,10,2)
  Out:
  In : range(0,10,2)
  Out:
  ####元组###
  In : t = (1,2,3,4)      ###定义元组用()###
  In : t            ###索引###
  Out: 1
  In : t
  Out: 3
  In : t[-1]
  Out: 4
  In : t[:]            ###切片###
  Out: (1, 2, 3, 4)
  In : t
  Out: (2, 3)
  In : t(0)=10      ###不可以对元组进行修改###
  File "<ipython-input-143-a7946ca4067e>", line 1
  t(0)=10
  SyntaxError: can't assign to function call
  In : name,age,gender=('fentiao',5,'male')    ###元组可以多个赋值###
  In : print name,age,gender
  fentiao 5 male
  In : a,b,c = 1,2,3
  In : print a,b,c
  1 2 3
  In : a,b,c = (1,2,3)
  In : print a,b,c
  1 2 3
  In : a=(1)
  In : type(a)
  Out: int
  In : a=("hello")
  In : type(a)
  Out: str
  In : a=("hello",)      ###如果要定义单个元组,需要加逗号###
  In : type(a)
  Out: tuple
  In : t = (1,2,(1,2),)    ###元组里的元素类型可以是多种的###
  In : type(t)
  Out: tuple
  In : t=10      ###可以对元组的类型为列表的元素赋值###
  In : t
  Out: (1, 2, (1, 2), )
  In : t = (1,2,3)*3
  In : t
  Out: (1, 2, 3, 1, 2, 3, 1, 2, 3)
  In : t1 = ('hello','world')
  In : t2 = ('westos','linux')
  In : print t1+t2
  ('hello', 'world', 'westos', 'linux')
  ######集合######
  集合是一个无序的,不重复的数据组合
  应用:
  1 列表去重
  2 关系测试:如交集,差集,并集的关系测试
  集合一般不能定义为空,定义为空的话,会变成字典型
  n : set = {}
  In : type(set)
  Out: dict
  In :
  小练习:输入一个英文句子,显示词的种类(去重)
  a = raw_input("请输入一个英文句子:")
  b = a.split()
  lengthen = len(b)
  print lengthen
  c = set(b)
  lengthen = len(c)
  print lengthen
  执行结果:
  /usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/4.py
  input english:i like english very very much
  5
  Process finished with exit code 0
  list1 =
  s1 = set(list1)
  print s1
  # print type(list1),type(s1)
  s2 = {1,2,100,'hello'}
  print s1.union(s2)      ###s1与s2的并集###
  print s1.intersection(s2)    ###s1与s2的交集###
  s1.intersection_update(s2)    ###将s1与s2的交集更新给s1###
  print s1
  print s1.difference(s2)      ###差集###
  print s1.symmetric_difference(s2)    ###对等差分###
页: [1]
查看完整版本: python基础2