python3学习笔记之字符串

字符串

  1、一个个字符组成的有序的序列,是字符的集合;
  2、使用单引号、双引号、三引号引住的字符序列
  3、字符串是不可变对象
  4、python3起,字符串就是Unicode类型;

字符串特殊举例:

  不对\n或者\t做处理的三种方式:

    test=r'hello \n word'

    test=R'hello \n word'

    test='hello \\n word'  #对\n进行转译

字符串元素访问

  1、字符串支持下标访问 

    t='hello word'
    print(t[2])

   2、字符串的每个字符都是有序序列,可以被迭代    

    t='hello word'
    for i in t:
      print(i)

    print(list(t))  #用list模块可以将字符串以列表的形式打印出来;

    ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'd']

字符串join连接

  "string".join(iterable) --> str
  将可迭代对象连接起来,使用string作为分隔符;
  可迭代对象本身元素都是字符串
  返回一个新的字符串

    t='hello word'
    print("-".join(t))

    返回结果:h-e-l-l-o- -w-o-r-d

  注意:python是强类型语言,字符串的拼接不能用到int型数字上,需要用map函数转化;

    lst=list(range(5))
    print("-".join(map(str,lst)))

    返回结果:0-1-2-3-4    

    a=list(range(5))
    print(list(map(str,a)))

    返回结果:['0', '1', '2', '3', '4']

字符串“+”号的连接  

    print("aaa"*2)
    print("bbb"+"aaa")

    返回结果:     

    aaaaaa
    bbbaaa

字符串的分割

  split(sep=None,maxsplit=-1) --> list of strings  从左至右
  sep指定分割字符串;缺省情况下空白字符串作为分割符
  maxsplit指定分割的次数,-1表示遍历整个字符串;
  rsplit 从右至左切

    t='hewllo wowrd'
    print(t.split("w"))
    print(t.split("w",maxsplit=1))
    print(t.split("w",maxsplit=2))
    print(t.split("w",maxsplit=3))
    print(t.split("w",maxsplit=4))

      注:maxsplit可以直接省略不写"print(t.split("w",3))"

    执行结果:    

    ['he', 'llo ', 'o', 'rd']    #默认跟据出现的所有w做切割;
    ['he', 'llo wowrd']     #从左到右,用第一个w切割;
    ['he', 'llo ', 'owrd']    #从左到右,用前两个w切割;

    ['he', 'llo ', 'o', 'rd']    #从左到右,用前三个w切割;
    ['he', 'llo ', 'o', 'rd']    #如果超出指定的次数,则默认跟据出现的所有w做切割;

字符串大小写

  upper() 全大写
  lower() 全小写
  swapcase() 交互大小写   

    t='hello word'
    print(t.upper())
    d='HELLO WORD'
    print(d.lower())

    c='Hello Word'
    print(c.swapcase())

    执行结果:   

    HELLO WORD
    hello word
    hELLO wORD

字符串排版

  title() 标题每个字母都大写
  capitalize() 首个单词大写
  center(width[,fillchar])
  width 打印宽度
  fillchar 填充的字符
  zfill(width)
  width 打印宽度,居右,左边用0填充;
  ljust(width[,fillchar])  #str左对齐
  rjust(width[,fillchar])  #str右对齐    

    t='hello word'
    print(t.title())
    print(t.capitalize())
    print(t.center(20,"*"))
    print(t.zfill(20))
    print(t.ljust(20,"*"))
    print(t.rjust(20,"*"))

    执行结果:    

    Hello Word
    Hello word
    *****hello word*****
    0000000000hello word
    hello word**********
    **********hello word

字符串的修改

  replace(old,new[,count])
  字符串中找到匹配替换为新子串,返回新的字符串;
  count表示替换几次,不指定就是全部替换;
  strip([chars])
  从字符串两端去除指定的字符集chars中的所有字符;
  如果chars没有指定,去除两端的空白字符;
  lstrip() 从左开始
  rstrip() 从右开始

    示例:   

    t=' hello word hello wordh '
    print(t.replace("w","W",1))    #小写w替换为大写w;并且替换1次;
    print(t.strip("h"))   #去除两端的h;
    print(t.lstrip("h"))  #去除左边的h字符串;
    print(t.rstrip("h"))  #去除右边的h字符串;

    返回结果:    

    hello Word hello wordh
    ello word hello word
    ello word hello wordh
    hello word hello word

字符串查找

  find(sub[,start[,end]])
  在指定的区间[start,end);从左至右,查找子串sub,找到返回索引,没找到返回-1;
  rfind(sub[,start[,end]])
  在指定的区间[start,end);从右至左,查找子串sub,找到返回索引,没找到返回-1;
  index(sub[,start[,end]])
  在指定的区间[start,end);从左至右,查找子串sub,找到返回索引,没找到则抛出异常ValueError
  count(sub[,start[,end]])
  在指定的区间[start,end);从左至右,统计子串sub出现的次数;

  时间复杂度
  index和count方法都是O(n)
  随着列表数据规模的增大,而效率下降;
  len(string)
  返回字符串的长度,即字符的个数;

  #enumerate()  该函数可以显示字符串下标  

  s = "i love you"
  list(enumerate(s))

    示例:

      t='hello word hello hello'
      print(list(enumerate(t)))
      print(t.find("h",12))
      print(t.index("h",12))
      print(t.count("h"))

    运行返回结果:

      [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o'), (5, ' '), (6, 'w'), (7, 'o'), (8, 'r'), (9, 'd'), (10, ' '), (11, 'h'), (12, 'e'), (13, 'l'), (14, 'l'), (15, 'o'), (16, ' '), (17, 'h'), (18, 'e'), (19, 'l'), (20, 'l'), (21, 'o')]
      17
      17

      3

字符串判断

  endswith(suffix[,start[,end]]) -> bool
  在指定的区间[start,end),字符串是否是suffix结尾
  startswith(prefix[,start[,end]]) -> bool
  在指定的区间[start,end),字符串是否是prefix开头

    t='hello word'
    print(list(enumerate(t)))
    print(t.endswith("o",5,8))  #在5到8的区间内,是否是以字母o结尾;
    print(t.startswith("l",3,5))  #在3到5区间内,是否是以字母i开头;

    执行结果:

    [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o'), (5, ' '), (6, 'w'), (7, 'o'), (8, 'r'), (9, 'd')]

    True

    True

  is系列
    isalnum()bool是否是字母和数字组成;
    isalpha()是否是字母
    isdecimal()是否只包含十进制数字
    isdigit()是否全部数字(0--9)
    isidentifier()是不是字母和下划线开头,其他都是字母数字下划线;
    islower()是否全部小写
    isupper()是否全部大写
    isspace()是否只包含空白字符

      示例:  

      a='123hello'
      print(a.isalnum()) 

      执行结果:

      True

字符串格式化

  字符串的格式化是一种拼接字符串输出样式的手段;
  join拼接只能是用分隔符,且要求被拼接的是可迭代对象;
  +拼接字符串方便,但是非字符串需要先转换为字符串才能拼接;

  占位符:使用%和格式字符组成,例如%s,%d;
  s调用str();r会调用repr();所有对象都可以被这两个转换;
  占位符中还可以插入修饰字符,例如%03d表示打印3个位置,不够前面补0;
  format % vlaues;格式字符串和被格式的值之间使用%分隔;
  values只能是一个对象,或是一个和格式字符串占位符数目相等的元组,或一个字典;

format()函数

  format函数格式字符串语法--python鼓励使用
  "{}{xxx}".format(*args,**kwargs) --> str
  args是位置参数,是一个元组;
  kwargs是关键字参数,是一个字典;
  花括号表示占位符;
  {}表示按照顺序匹配位置参数,{n}表示取位置参数所以为n的值;
  {xxx}表示在关键字参数中搜索名称一致的;
  {{}}表示打印花括号;

浮点数

  print("{}".format(3**0.5))
  print("{:g}".format(3**0.5))
  print("{:f}".format(3**0.5))
  print("{:10f}".format(3**0.5)) ##右对齐
  print("{:2}".format(3**0.5)) ##宽度为2
  print("{:.2}".format(3**0.5)) ##2个数子
  print("{:.2f}".format(3**0.5)) ##保留2为小数
  print("{:3.2f}".format(3**0.5)) ##宽度为3,小数点后2位
  print("{:3.3f}".format(0.2745))
  print("{::3.3%}".format(1/3))

bytes / bytearray

  python3 引入两个新的类型
  bytes:不可变字节序列
  bytes是字节组成的有序的不可变序列
  使用b前缀定义
  只允许基本的ascii使用的字符形式b'abc9'
  使用16禁止表示b"\x41\x61"
  bytearray:
  字节组成的有序的可变序列
  从一个字节序列或者buffer复制出一个新的可变的bytearray对象
  编码与解码
  字符串按照不同的字符集编码encode返回字节序列bytes
  encode(encoding='utf-8',errors='strict') --> bytes
  字节序列按照不哦她那个的字符集解码decode返回字符串
  bytes.decode(encoding="utf-8",errors="strict") --> str
  bytearray.decode(encoding="utf-8",errors="strict") --> str

  

posted @ 2020-04-12 23:42  潇湘神剑  阅读(230)  评论(0编辑  收藏  举报