字符串

  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

  

python3学习笔记之字符串的更多相关文章

  1. python3学习笔记(7)_listComprehensions-列表生成式

    #python3 学习笔记17/07/11 # !/usr/bin/env python3 # -*- conding:utf-8 -*- #通过列表生成式可以生成格式各样的list,这种list 一 ...

  2. python3学习笔记(6)_iteration

    #python3 学习笔记17/07/10 # !/usr/bin/env python3 # -*- coding:utf-8 -*- #类似 其他语言的for循环,但是比for抽象程度更高 # f ...

  3. Python3学习笔记(urllib模块的使用)转http://www.cnblogs.com/Lands-ljk/p/5447127.html

    Python3学习笔记(urllib模块的使用)   1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None,  ...

  4. 1.C#基础学习笔记3---C#字符串(转义符和内存存储无关)

    技术qq交流群:JavaDream:251572072  教程下载,在线交流:创梦IT社区:www.credream.com ------------------------------------- ...

  5. Python3学习笔记 - 准备环境

    前言 最近乘着项目不忙想赶一波时髦学习一下Python3.由于正好学习了Docker,并深深迷上了Docker,所以必须趁热打铁的用它来创建我们的Python3的开发测试环境.Python3的中文教程 ...

  6. python3学习笔记(5)_slice

    #python3 学习笔记17/07/10 # !/usr/bin/env python3 # -*- coding:utf-8 -*- #切片slice 大大简化 对于指定索引的操作 fruits ...

  7. 【学习笔记】字符串—马拉车(Manacher)

    [学习笔记]字符串-马拉车(Manacher) 一:[前言] 马拉车用于求解连续回文子串问题,效率极高. 其核心思想与 \(kmp\) 类似:继承. --引自 \(yyx\) 学姐 二:[算法原理] ...

  8. 「学习笔记」字符串基础:Hash,KMP与Trie

    「学习笔记」字符串基础:Hash,KMP与Trie 点击查看目录 目录 「学习笔记」字符串基础:Hash,KMP与Trie Hash 算法 代码 KMP 算法 前置知识:\(\text{Border} ...

  9. python3学习笔记(8)_sorted

    # python学习笔记 2017/07/13 # !/usr/bin/env python3 # -*- coding:utf-8 -*- #python 内置sorted()函数 可以对list进 ...

随机推荐

  1. Open Harmony移植:build lite配置目录全梳理

    摘要:本文主要介绍build lite 轻量级编译构建系统涉及的配置目录的用途,分析相关的源代码. 本文分享自华为云社区<移植案例与原理 - build lite配置目录全梳理>,作者:z ...

  2. CSS书写及命名规范

    1.样式书写顺序 positioning定位::position.display.float.top. right.bottom.left.overflow.clear.z-index: box mo ...

  3. django三板斧与request对象方法与ORM

    目录 django三板斧 HttpResponse() render() redirect() 网页获取静态文件样式 request对象方法 post请求问题 针对get请求和post请求执行不同代码 ...

  4. MongoDB 分片集群

    每日一句 Medalist don't grow on trees, you have to nurture them with love, with hard work, with dedicati ...

  5. 测试平台系列(94) 前置条件该怎么支持Python呢

    回顾 上一节我们狠狠操练了一番oss,但我们的任务还很长久,所以我们需要继续打磨我们的功能. 那今天就让我们来思考下,如何在前置条件支持python脚本,多的不说,我们也暂时不考虑其他语言,因为光考虑 ...

  6. MySQL、SqlServer、Oracle,这三种数据库的优缺点,你知道吗?

    盘点MySQL.SqlServer.Oracle 三种数据库优缺点 MySQL SqlServer Oracle 一.MySQL 优 点 体积小.速度快.总体拥有成本低,开源:支持多种操作系统:是开源 ...

  7. Spring-Cloud-Alibaba系列教程(一)Nacos初识

    前言 在2020年即将开启SpringCloudAlibaba的专题,希望2020年共同学习进步. 学习资料 文档 Naco文档 程序猿DD Spring Cloud Aliabab专题 专题博客 视 ...

  8. net core天马行空系列-微服务篇:全声明式http客户端feign快速接入微服务中心nacos

    1.前言 hi,大家好,我是三合,距离上一篇博客已经过去了整整两年,这两年里,博主通关了<人生>这个游戏里的两大关卡,买房和结婚.最近闲了下来,那么当然要继续写博客了,今天这篇博客的主要内 ...

  9. 架构师必备:系统容量现状checklist

    正如飞机在起飞前,机长.副机长要过一遍checklist检查,确认没问题了才能起飞.楼主也整理了一个系统容量现状checklist,方便对照检查.本文搭配架构师必备:如何做容量预估和调优,食用更佳. ...

  10. 17.Nginx 重写(location rewrite)

    Nginx 重写(location / rewrite) 目录 Nginx 重写(location / rewrite) 常见的nginx正则表达式 location lication的分类 loca ...