zoukankan      html  css  js  c++  java
  • python字符串操作

    1、字符串定义:
      1>一个个字符组成的有序的序列,是字符的集合,是可迭代对象,可索引
      2>使用单引号、双引号、三引号引住的字符序列,r前缀,f前缀
      3>字符串是不可变对象
      4>Python3起,字符串就是Unicode类型

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'hello'
    for i in s1:                      #可迭代
        print(i)
    print("索引值为1的元素:",s1[1]) #可索引 执行结果: h e l l o
    索引值为1的元素: e
    s2 = 'hello
    beijing'    #
    :换行符
    print('s2:',s2)
    s3 = r'hello
    beijing'   #r前缀:转义
    ,当字符串输出
    print('s3:',s3)
    s4 = 'ni'
    s5 = 'hao'
    s6 = "{s4} -> {s5}"
    print('s6:',s6)
    s7 = f"{s4} -> {s5}" #f前缀:引用
    print('s7:',s7)

    执行结果: s2: hello beijing s3: hello beijing
    s6: {s4} -> {s5}
    s7: ni -> hao

    2、join连接字符串:
      将可迭代对象连接起来,使用string作为分隔符
      可迭代对象本身元素都是字符串
      返回一个新的字符串

    Signature: str.join(self, iterable, /)
    Docstring:
    Concatenate any number of strings.
    
    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.
    
    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
    Type:      method_descriptor

      在可交互式python操作(如:jupyter)中可看到,join会立即返回返回一个新的字符串

       在PyCharm中可以使用print()输出

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    print('+'.join(map(str,range(10))))    #map函数:映射,把一个个数字转换成str
    print('
    '.join(map(str,range(10))))
    
    执行结果:
    0+1+2+3+4+5+6+7+8+9
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

    3、+ → str
    将两个字符串连接在一起,返回一个新字符串

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'hello'
    s2 = 'world'
    print(s1 + s2)    #字符串不可变,字符串相加产生新字符串
    s3 = s1 + s2
    s3 += s2          #等价:s3 = s3 + s2
    print(s3)
    
    执行结果:
    helloworld
    helloworldworld

    4、字符串分割
      分割字符串的方法分为2类
      1>split
        将字符串按照分隔符分割成若干字符串,并返回列表
        rsplit(sep=None,maxsplit=-1) → list of strings
          从右向左切割
          sep指定分割字符串,缺省的情况下空白字符串作为分隔符
          maxsplit指定分割次数,-1表示遍历整个字符串

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'a,b,c,d,e,f'
    print(s1.split())       #默认使用空白字符分割,立即返回一个列表
    print(s1.split(','))    #以','分割
    print(s1.split(',',maxsplit=2))    #指定分割次数2次
    print(s1.split(',',maxsplit=-1))   #maxsplit=-1,遍历整个字符串,相当于不指定maxsplit
    print(s1.rsplit(',',maxsplit=2))   #从右向左切
    
    执行结果:
    ['a,b,c,d,e,f']
    ['a', 'b', 'c', 'd', 'e', 'f']
    ['a', 'b', 'c,d,e,f']
    ['a', 'b', 'c', 'd', 'e', 'f']
    ['a,b,c,d', 'e', 'f']

        splitlines([keepends]) → list of strings
            按行来切割字符串

            keepends指的是是否保留行分割符
            行分割包括 、 、 等

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'I
     am
     	super
     man'
    print(s1.splitlines())    #以换行符切割
    print(s1.splitlines(True))    #保留换行符字符
    print(s1.splitlines(False))   #不保留换行符字符,默认就是
    
    执行结果:
    ['I', ' am', ' 	super', ' man']
    ['I
    ', ' am
    ', ' 	super
    ', ' man']
    ['I', ' am', ' 	super', ' man']


    2>partition系
        将字符串按照分隔符分割成2段,返回这2段和分隔符的元组
        partition(sep) → (head, sep, tail)
        从左至右,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果没有找到分隔符,就返回头、2个空元素的三元组
        sep分割字符串,必须指定

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'a,b,c,d,e,f'
    print(s1.partition(','))    #立即返回一个三元组,切一刀 split(maxsplit=1)
    print(s1.rpartition(','))   #从右向左切
    print(s1.partition('c,d'))  #以'c,d'切割
    print(s1.split('c,d'))      #split与partition的差别
    
    执行结果:
    ('a', ',', 'b,c,d,e,f')
    ('a,b,c,d,e', ',', 'f')
    ('a,b,', 'c,d', ',e,f')
    ['a,b,', ',e,f']

    5、大小写
      upper()
        全大写
      lower()
        全小写
      大小写,做判断的时候用
      swapcase()
        交换大小写

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    print('aBcD' == 'abcd')    #不相等,返回False
    print('aBcD'.lower() == 'abcd')    #将'aBcD'转换为全小写比较
    print('abCD'.upper() == 'ABCD')    #将'abCD'转换为全大写比较
    print('ABcd'.swapcase())   #将大写转换为小写,将小写转换为大写
    
    执行结果:
    False
    True
    True
    abCD

    6、字符串编排
      title() → str
          标题的每个单词都大写
      capitalize() → str
          首个单词大写
      center(width[, fillchar]) → str
          width打印宽度
          fillchar填充的字符
      zfill(width) → str
          width打印宽度,居右,左边用0填充
      ljust(width[, fllchar]) → str左对齐
      rjust(width[, fillchar]) → str右对齐
      中文用的少,了解一下

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'i am super man'
    print(s1.title())       #首字母大写
    print(s1.capitalize())  #首单词大写
    print(s1.center(30,'#'))    #居中
    print(s1.zfill(30))         #居右,左边用0填充
    print(s1.ljust(30,'0'))     #居左
    print(s1.rjust(30,'0'))     #居右
    
    执行结果:
    I Am Super Man
    I am super man
    ########i am super man########
    0000000000000000i am super man
    i am super man0000000000000000
    0000000000000000i am super man

    7、字符串修改
      replace(old, new[, count]) → str
      字符串中找到匹配替换为新子串,返回新字符串
      count表示替换几次,不指定就是全部替换

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = '1 2 2 2 3 3 4 5'
    print(s1.replace('2','22'))
    print(s1.replace('2','22',1))
    
    执行结果:
    1 22 22 22 3 3 4 5
    1 22 2 2 3 3 4 5

      strip([chars]) → str
        从字符串两端去除指定的字符集chars中的所有字符
        如果chars没有指定,去除两端的空白字符
      lstrip    从左开始
      rstrip    从右开始

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = '   I am super man    '
    print(s1.strip())    #不指定,默认去除两边的空格
    print(s1.strip(' Iamn'))     #指定则从指定中匹配
    
    执行结果:
    I am super man
    super

    8、字符串查找
      find(sub[, start[, end]) → int
        在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到返回-1
      rfind(sub[, start[, end]]) → int
        在指定的区间[start, end),从右至左,查找子串sub。找到返回索引,没找到返回-1

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'I am super man'
    print(s1.index('I'))    #检索值返回结果,未检索到的话会报错
    print(s1.find('s'))     #检索值返回索引,未检索到返回-1
    print(s1.find('A'))
    
    执行结果:
    0
    5
    -1

      count(sub[, start[ end]) → int
        在指定的区间[start, end),从左至右,统计子串sub出现的次数

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

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

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    s1 = 'xxx.tar.gz'
    print(s1.endswith('.gz'))          #判断是否以.gz结尾
    print(s1.endswith('.tar',0,-3))    #[0,-3) 判断.tar
    print(s1.startswith('xxx'))        #判断是否以xxx开头
    
    执行结果:
    True
    True
    True

    10、字符串判断is系列

    isalnum() → bool  是否是字母和数字组成
    isalpha()         是否是字母
    isdecimal()       是否只包含十进制数字
    isdigit()         是否全部数字(0~9)
    isidentifier()    是标识符嘛,字母和下划线开头,其他都是字母、数字、下划线
    islower()         是否都是小写
    isupper()         是否全部大写
    isspace()         是否只包含空白字符
    # -*- coding:utf-8 -*-
    # version:python3.7
    
    a = input('>>>')
    if a.isdigit():    #判断是否为数字
        print('number')
    else:
        print('not number')
    
    执行结果:
    >>>tr
    not number

    11、字符串格式化
      字符串的格式化是一种拼接字符串输出样式的手段,更灵活方便
        join拼接只能使用分隔符,且要求被拼接的是可迭代对象且其元素是字符串
        +拼接字符串还算方便,但是非字符串需要先转换为字符串才能拼接
      在2.5版本之前,只能使用printf style风格的print输出,2.5版本之后建议使用format函数风格
        1>printf-style formatting,来自于C语言的printf函数
        格式要求:
          占位符:使用%和格式字符组成,例如%s、%d(字符串、数字)等
            s调用str(),r会调用repr()。所有对象都可以被这两个转换。
          占位符中还可以插入修饰字符,例如%03d表示打印3个位置,不够前面补零

    # C风格:
    # -*- coding:utf-8 -*-
    # version:python3.7
    
    # -*- coding:utf-8 -*-
    # version:python3.7
    
    print("My name is %s,I am %d" % ('zhang',20))    #格式:字符模板(格式化字符) % 字符;%s->str %d->digit
    print("I am %04d" % 20)    #长度为4,多余位用0补齐
    print("I am %-4d" % 20)    #长度为4,"-"负号表示左对齐,默认右对齐
    print("%f" % 32.2456)      #%f:浮点数,默认小数点后保留6位
    print("%14.2f" % 32.2456)  #长度为14位,精度为2(小数点后保留2位)
    print("%x" % 127)          #%x表示十六进制,X表示大写
    print("%#X" % 127)         #"#"号表示0X前缀
    
    执行结果:
    My name is zhang,I am 20
    I am 0020
    I am 20  
    32.245600
             32.25
    7f
    0X7F

        2>format % values,格式字符串和被格式的值之间使用%分隔
          values只能是一个对象,或是一个与格式字符串占位符数目相等的元组,或一个字典

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

    # -*- coding:utf-8 -*-
    # version:python3.7
    
    #不常用,了解即可,通常不定义前面占位符,不写死,一般在位置参数处定义
    print("{} {}".format(1,2,3))    #允许后面超位
    print("{2[0]} {1} {0}".format('a','b',['c']))    #支持索引,索引和位置对应不能混用,否则会报错
    print("{name} {0} {1}".format('127.0.0.1',80,name='My server name is super PC'))
    
    执行结果:
    1 2
    c b a
    My server name is super PC 127.0.0.1 80
    # 进制
    # -*- coding:utf-8 -*- # version:python3.7
     print("{:#02x}{:02x}{:02x}{:02x}".format(127,100,10,20)) #02表示宽度为2,不够用0补,用16进制表示ip地址 print("int:{0:d}; hex:{0:x}; oct:{0:o}; bin:{0:b}".format(42))
    print("int:{0:d}; hex:{0:#x}; oct:{0:#o}; bin:{0:#b}".format(42))
    执行结果:
    0x7f640a14
    int:42;  hex:2a;  oct:52;  bin:101010
    int:42;  hex:0x2a;  oct:0o52;  bin:0b101010
    # 对齐
    # -*- coding:utf-8 -*-
    # version:python3.7
    
    print("{}*{}={:02}".format(2,3,2*3))      #长度为2,默认右对齐,不够用0补
    print("{}*{}={:<2}".format(2,3,2*3))      #长度为2,左对齐
    print("{}*{}={:#^20}".format(2,3,2*3))    #长度为20,居中,用"#"号填充
    
    执行结果:
    2*3=06
    2*3=6 
    2*3=#########6##########
    # 时间格式
    # -*- coding:utf-8 -*-
    # version:python3.7
    
    import datetime    #模块
    d = datetime.datetime.now()
    print(d)
    print("{:%Y-%m-%d %H:%M:%S}".format(d))    #冒号":",前面表示位置对应,0省略
    
    执行结果:
    2020-03-20 19:03:04.315352
    2020-03-20 19:03:04
    # 浮点数
    # -*- coding:utf-8 -*-
    # version:python3.7
    
    print("{}".format(3**0.5))       #1.7320508075688772
    print("{:f}".format(3**0.5))     #1.732051   f:浮点数,精度默认为6
    print("{:10f}".format(3**0.5))   #右对齐,宽度为10
    print("{:3f}".format(3**0.5))    #注意:宽度可以被撑破,前面定义宽度为3,结果宽度大于3
    print("{:.2}".format(3**0.5))    #1.7   2个数字,科学记数法
    print("{:.2f}".format(3**0.5))   #1.73   小数点后2位
    print("{:3.2f}".format(3**0.5))  #1.73   宽度为3,小数点后2位
    print("{:20.3f}".format(0.2745)) #0.275   默认右对齐
    print("{:3.3%}".format(1/3))     #33.333%
    
    执行结果:
    1.7320508075688772
    1.732051
      1.732051
    1.732051
    1.7
    1.73
    1.73
                   0.275
    33.333%

      建议使用format函数格式化字符串

  • 相关阅读:
    开博客啦
    C语言 变长参数表的使用方法
    禅道程序员
    【转】函数式编程另类指南
    Servlet中JSP页面跳转的两种方法以及其区别
    《C程序设计语言》(学习笔记)——结构体
    C#保存wps和office表格.数据源为list<T>类型
    中国网建的短信接口实现
    C#保存wps和office表格.数据源为list<T>类型,
    MD5加密
  • 原文地址:https://www.cnblogs.com/zyybky/p/12524320.html
Copyright © 2011-2022 走看看