python基础2

1、格式化输出

  • 占位符%
    • s ->字符串 ,d -> 数字
    • 在使用%的格式化输出时,如果本身就是要%,可以使用两个百分号表示一个,%%
    • name = input()
      s = 'my name is %s' %(name)
  • format
    • #形式1
      res = '{} {} {}'.format('hsr', 22, 'male')
      
      #形式2
      res = '{0} {1} {2}'.format('hsr', 22, 'male')
      
      #形式3
      res = '{name} {age} {sex}'.format(name='hsr', age=22, sex='male')

 

2、and和or

#1
6 or 3 < 2

#2
8 or 3 and 4 or 2 and 0 or 9 and 7

#3
0 or 2 and 3 and 4 or 6 and 0 or 3

#4
3 and 2 > 1

 

3、类型转换

#int -> str
i = 1
s = str(i)

#str -> int
s = '123'
i = int(s)

#int->bool
i = 3
b = bool(i) #非0 -> True,0 ->False

#bool -> int
b = True
i = int(b) #True -> 1, False -> 0

#str -> bool
s = 'a'
b = bool(s) #非空字符串为真,空为假

 

3、字符串

  • 索引
    • 就是下标,从0开始
    • s = 'abc'
      s1 = s[0] #s1 = 'a'
  • 切片
    • 通过索引(索引1:索引2:步长)截取字符串的一段(包含索引1,不含索引2)
    • s = 'ABCDEFGHIJK'
      
      s1 = s[0:3] #ABC
      
      s2 = s[:] #ABCDEFGHIJK
      
      s3 = s[::2] #ACEGIK
      
      s4 = s[::-1] #KJIHGFEDCBA
  • 字符串操作
    • 第一个字母大写
      s.capitalize()
    • 全部大写
      s.upper()
    • 全部小写
      s.lower()
    • 大小写翻转
      s.swapcase()
    • 每个单词的首字母大写
      s.title()
    • 字符居中
      s.center(length,f) #f默认是空格
    • 长度
      len(s)
    • 判断是否以某子串开头
      s.startswith(f) #f为某个子串
    • 判断是否以某子串结尾
      s.endswith(f) #f为某个子串
    • 查找是否包含某子串
      s.find(f) #f为某子串,找到返回索引
      
      #s.index(f) 有用同样的作用,但如果找不到会报错,而find会返回-1
    • 去除前后空格
      s.strip() #可以添加参数,比如strip('#')可以去除前后的#
      
      #只删除前面的
      s.lstrip()
      
      #只删除后面的
      s.rstrip()
    • 统计包含某元素的个数
      s.count(f) #f为某子串
    • 按某符号分割成列表
      s.split(f) #例如 s = 'a;b;c;d'
      # s.split(';')  得到 ['a','b','c','d']
    • 替换
      s = '今天是星期六'
      s.replace('''') #得到 '今天是星期日'

       

 

posted @ 2019-02-09 13:01  WaltHwang  阅读(141)  评论(0编辑  收藏  举报