美文网首页
python入门 第二天 str

python入门 第二天 str

作者: xinmin | 来源:发表于2018-08-02 22:05 被阅读0次
  • 编码与解码
    # -*- coding:utf-8 -*-
    # python2.x中使用
    temp = "张三"
    # 解码需要指定原来是什么编码
    temp_unicode = temp.decode("utf-8")
    print(temp_unicode)
    # temp_gbk = temp_unicode.encode("gbk")
    # print(temp_gbk)
    # windows终端需要gbk
    
  • 算数运算符
    • +、-、*、/、%、**、//:加、减、乘、除、模(取余数)、幂、取整除
    • python3.x与python2.x的区别
      • py2: 9/2 = 4 ,导入模块form _future import division则可以解决
      • py3:9/2 = 4.5
  • 其他运算符
    • ==、!=(<>)、>=、<=:关系运算符
    • in、not in:成员运算符,返回true或false`
    • and、or、not:逻辑运算符
  • 新增的基本数据类型
    • 列表:list
    • 元组:tuple
  • 查看对象的类,或对象所具备的功能
    # 查看所具有的方法
    temp = "xinmin"
    print(dir(temp))
    # 查看具体的方法实现
    help(type(temp))
    
  • int 的内置方法常用
    bit_length:获取数字表示成二进制的最短位数
    n = 4
    ret = n.bit_length()
    print(ret) # 100
    
  • 字符串(str)常用方法
    • capitalize():首字母变大写
      n = "xinmin"
      ret = n.capitalize()
      print(ret) # Xinmin
      
    • center():内容居中
      n = "xinmin"
      # 居中两边用_填充
      ret = n.center(20, '_')
      print(ret) # _______xinmin_______
      
    • count():统计字母出现的次数
      n = "xinmin"
      ret = n.count('i')
      print(ret) # 2
      # 0-3位置中i出现的次数
      res = n.count('i', 0, 3)
      print(res) # 1
      
    • endswith():判断是否已某个字母结尾
      n = "xinmin"
      ret = n.endswith('n')
      print(ret) # True
      # 获取0-4不包含4位置是否i结尾
      res = n.count('i', 0, 4)
      print(res) # False
      
    • expandtabs():把tab间转换成空格键
      n = "xinmin\t110"
      print(n)
      ret = n.expandtabs()
      print(n)
      
    • find():找对应的字母返回下标,包含多个时返回第一个的下标,没有找到返回-1
      n = "xinmin"
      ret = n.find('i')
      print(n) # 1
      
    • format():格式化字符串
      s = "hello {0}, age {1}"
      new1 = s.format('xinmin', 19)
      print(new1) # hello xinmin, age 19
      
    • index():同find(),没找到报错,所以选择用find()
    • join():连接
      # list集合,元组也支持 li = ("xin", "min")
      li = ["xin","min"]
      # 字符串以下划线连接
      s = "_".join(li)
      print(s) # xin_min
      
    • lstrip():去左边空格
    • rstrip():去右边空格
    • strip():去左右两边空格
    • partition():替换
      s = "xinmin is NB"
      ret = s.partition('is') 
      print(ret) # ('xinmin ', 'is', ' NB') 元组类型
      
    • replace():替换
    • swapcase():大写变小写,小写变大写
    • upper():小写变大写
  • str的索引与切片
    s = "xinmin"
    # 索引
    print(s[0])  # x
    print(s[1])  # i
    print(s[2])  # n
    # 长度
    ret = len(s)
    print(ret) # 6
    # 切片 0=< 0,1,2,3 <= 4
    print(s[0:4]) # xinm
    # for循环,break,continue仍适用
    for item in s:
        print(item)
    # while 循环
    start = 0
    while start < len(s)
         temp = s[start]
         print(temp)
         start += 1
    

相关文章

网友评论

      本文标题:python入门 第二天 str

      本文链接:https://www.haomeiwen.com/subject/wzckvftx.html