• python字符串类型


    字符串类型

    一、字符串(str)

    1.1作用

    可以用来表示姓名,爱好等

    1.2定义

    字符就相当于一个一个的山楂,字符串相当于一个糖葫芦。字符串就向糖葫芦一样将山楂,串联起来。字符串就像是一串被串联起来的字符,在单引号,双引号或者三引号内包裹的一串字符。

    1. 普通字符串的定义方式
    name1 = 'chen'
    name2 = "nick"
    print(id(name1))
    print(type(name1))
    print(name1)
    #输出:
    2793468686640
    <class 'str'>
    chen
    
    
    print(id(name2))
    print(type(name2))
    print(name2)
    #输出:
    2659224937200
    <class 'str'>
    nick
    
    1. 三引号内的字符串定义:

      ​ 需要注意的是,

      三引号内的字符是可以换行的,换行的时候会输出换行

    name3 = """chen
    nick
    """
    
    print(name3)
    #输出:
    chen
    nick
    
    
    
    name4 = '''chen
    nick
    '''
    print(name4)
    #输出:
    
    chen
    nick
    
    
    
    
    1. 二进制字符串的定义方式
    #打印出来bytes,二进制类型的定义方式。
    s=b'chen'
    print(s)
    print(type(s))
    #输出:
    b'chen'
    <class 'bytes'>
    
    
    1. 带有特殊意义的符号定义字符串

      s='ch
      en'  #
      换行
      print(s)
      print(type(s))
      #输出:
      ch
      en
      <class 'str'>
      
      s='ch	en'  #	缩进4位
      print(s)
      print(type(s))
      #输出:
      ch	en
      <class 'str'>
      
      s='ch
      en' # 原位置打印
      print(s)
      print(type(s))
      #输出:
      en
      <class 'str'>
      
      
      s='c
      h
      e	n'
      print(s)
      print(type(s))
      #输出:
      c
      e	n
      <class 'str'>
      
      w=r'c
      h
      e	n'   #原生打印,取消特殊字符的意义
      print(w)
      print(type(w))
      
      #输出:
      c
      h
      e	n
      <class 'str'>
      

    二、如何用

    字符串只能加(+),乘(*)以及逻辑比较

    字符串的拼接,即重新申请一个小空间把俩个字符串都拷贝到一份后在拼接。而不是把一个小空间的变量值复制到另外一个变量的小空间内,然后拼接。

    msg2 = "my name is 'chen'"
    msg3 = "my name is 'chen'"
    print(msg2+msg3)
    #输出:
    my name is 'chen'my name is 'chen'
    

    输出:my name is 'chen'my name is 'chen'

    注意:如果字符串内有引号,则包裹字符串的引号和字符串内部的引号不能相同

    name = 'chen'
    print(name * 10)
    
    #输出:
    
    chenchenchenchenchenchenchenchenchenchen
    

    注意:字符串的乘法只能乘以数字。

    msg1 = 'hello'
    msg2 = 'z'
    print(msg1 > msg2)
    #输出:
    False
    

    注意:字符串比较大小,按照ASCII码比较,比较的是字母的顺序

    三、字符串类型的内置方法

    3.1 优先掌握

    1. 按索引取值(只能取不能改变)

      msg = 'hello python'
      print(f"索引为6:{msg[6]}")
      输出:
      索引为6: n
      
    2. 切片(顾头不顾尾)

      mag = 'hello chen'
      ###### h  e  l  l  o     c  h  e  n
      ###### 0  1  2  3  4  5  6  7  8  9  从前往后的索引序号
      ######-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 从后往前的索引序号
      ########顾头不顾尾
      
      
      print(mag[3])
      #输出 l
      print(mag[:])
      #输出 hello chen
      print(mag[3:])
      #输出 lo chen
      print(mag[:3])
      #输出 hel
      print(mag[3:8])
      #输出lo ch
      print(mag[::])
      #输出hello chen
      print(mag[::3])
      #输出 hlcn
      print(mag[:3:])
      #输出 hel
      print(mag[3::])
      #输出 lo chen
      print(mag[3:8:2])# 步长位2
      #输出 l h
      print(mag[3:8:])
      #输出 lo ch
      print(mag[3::2])
      #输出 l hn
      print(mag[:8:2])
      #输出 hloc
      print(mag[-2:-5:1])#正序
      #输出
      print(mag[-2:-5:-1])#倒叙
      #输出ehc
      print(mag[::-1])
      #输出nehc olleh
      
    3. 长度len

      mag = 'hello chen'
      print(len(mag))
      #输出:
      10
      
      
    4. 成员变量in or not in

      mag = 'hello chen'
      print('hello' in mag)#判断字符是否在字符串中
      # 输出:True
      print('chen' not in mag)
      # 输出:False
      
      
    5. 移除空白strip(移除的字符必须在两端)

      mag= '     chenshuai    '
      print(mag.strip())#去掉俩边空格
      ##输出:
      chen shuai
      
      
      mag = '&&&hello chen'
      
      print(mag.strip('&'))#指定多个字符,可以去掉
      #输出:hello chen
      print('&&&hello chen'.strip('& '))
      #输出:hello chen
      
    6. 切分split(默认以空格切割字符串)

      info="chen shuai"
      print(info.split())#默认以空格为切割符
      #输出:
      ['chen','shuai']
      
      
      
      
      ##split()选中一些符号或者字符
      info = "python:male:30"
      list1 = info.split(":")
      list2 = info.split(":", 0)  # 表示不切
      list3 = info.split(":", 1)  # 表示以':'为切割符,只切割第一个
      list4 = info.split(":", 2)  # 表示以':'为切割符,只切割前俩个
      list5 = info.split(":", -1)
      print('list1:',list1)
      print('list2:',list2)
      print('list3:',list3)
      print('list4:',list4)
      print('list5:',list5)
      
      输出:
      list1: ['python', 'male', '30']
      list2: ['python:male:30']
      list3: ['python', 'male:30']
      list4: ['python', 'male', '30']
      list5: ['python', 'male', '30']
      
    7. 循环

      mag = 'hello python'
      for i in mag:
          print(i)
          
          
          
      #输出 :
      h
      e
      l
      l
      o
       
      p
      y
      t
      h
      o
      n
      

    3.2需要掌握

    1. Istrip&rstrip

      mag = '&&hello python&&'
      print(mag.strip('&'))
      print(mag.lstrip('&'))##去除首部的
      print(mag.rstrip('&'))## 取出尾部的
      输出:
      hello python
      hello python&&
      &&hello python
      
    2. lower&upper

      mag = 'HELLO python'
      print(mag)
      print(mag.upper())##大写
      print(mag.lower())## 小写
      
      #输出:
      HELLO python
      HELLO PYTHON
      hello python
      
    3. startswith&endswith

      mag = 'HELLO python'
      print(mag.startswith('HELLO'))##检测以什么开头
      print(mag.endswith('python'))## 检测以什么结尾
      #输出:
      True
      True
      
      
    4. rsplit

      ## 从右边开始切割
      mag = 'hello:python:chen'
      print(mag.rsplit(':'))
      print(mag.rsplit(':',1))
      #输出:
      ['hello', 'python', 'chen']
      ['hello:python', 'chen']
      
    5. join

      # 拼接
      lis = [1,2,'19']
      print(':'.join(lis))  # 报错,数字不可和字符串拼接
      
      
      # str之join()
      lis = ['chen', 'male', '19']
      
      print(':'.join(lis))
      #输出
      chen:male:19
      
    6. replace

      msg = 'hello chen'
      print(msg.replace('chen','python'))#替换
      #输出:
      hello python
      
    7. isdigit

      #检测是否为整数
      salary = '111'
      print(salary.isdigit()) 
      #输出: True
      
      salary = '111.1'
      print(salary.isdigit())  
      #输出: False
      
    8. isalpha判断是否为字符

    3.3其他内置方法

    1. find|rfind|index|rindex|count
    2. center|ljust|rjust|zfill
    3. expandtabs
    4. captalize|swapcase|title
    5. is系列

    1.find()、rfind()、index()、rindex()、count()

    • find/rfind求索引,find('字符'),找到第一个,返回索引,找不到返回-1
    • index求索引 ,index('字符'),找到第一个,返回索引,找不到报错
    # str之find()、rfind()、index()、rindex()、count()
    msg = 'my name is tank, tank shi sb, hha'
    
    print(f"msg.find('tank'): {msg.find('tank')}")  # 找不到返回-1
    print(f"msg.find('tank',0,3): {msg.find('tank',0,3)}")
    print(f"msg.rfind('tank'): {msg.rfind('tank')}")  # 找不到返回-1
    print(f"msg.index('tank'): {msg.index('tank')}")  # 找不到报错
    print(f"msg.rindex('tank'): {msg.rindex('tank')}")  # 找不到报错
          
    
    print(f"msg.count('tank'): {msg.count('tank')}")
    msg.find('tank'): 11
    msg.find('tank',0,3): -1
    msg.rfind('tank'): 17
    msg.index('tank'): 11
    msg.rindex('tank'): 17
    msg.count('tank'): 2
    

    2.center()、ljust()、rjust()、zfill()

    • center以字符为中心
    • ljust让字符靠左
    • rjust让字符靠右
    • zfill字符前填充多少0
    # str之center()、ljust()、rjust()、zfill()
    print(f"'info nick'.center(50,'*'): {'info nick'.center(50,'*')}")
    print(f"'info nick'.ljust(50,'*'): {'info nick'.ljust(50,'*')}")
    print(f"'info nick'.rjust(50,'*'): {'info nick'.rjust(50,'*')}")
    print(f"'info nick'.zfill(50): {'info nick'.zfill(50)}")  # 默认用0填充
    'info nick'.center(50,'*'): ********************info nick*********************
    'info nick'.ljust(50,'*'): info nick*****************************************
    'info nick'.rjust(50,'*'): *****************************************info nick
    'info nick'.zfill(50): 00000000000000000000000000000000000000000info nick
    

    3.expandtabs()

    扩张,只针对字符串里面有 的字符串

    # str之expandtabs()
    print(f"a\tb\tc: %s"%('a	b	c	'))  # 默认制表符8个空格
    print(f"'a\tb\tc'.expandtabs(32): %s"%('a	b	c	'.expandtabs(32)))
    a	b	c: a  b   c   
    'a	b	c'.expandtabs(32): a                               b                               c                               
    

    4.captalize()、swapcase()、title():只针对单词

    • catalize():字符串的首字母大写
    • swapcase():大小写互换
    • title():标签,所有单词的首字母大写
    # str之captalize()、swapcase()、title()
    name = 'nick handsome sWAPCASE'
    
    print(f"name.capitalize(): {name.capitalize()}")
    print(f"name.swapcase(): {name.swapcase()}")  # 大小写互转
    print(f"name.title(): {name.title()}")
    name.capitalize(): Nick handsome swapcase
    name.swapcase(): NICK HANDSOME Swapcase
    name.title(): Nick Handsome Swapcase
    

    5.is数字系列(只是为了告诉你,判断是否为数字时除了中文数字以后使用isdigit()即可)

    • isdecimal(): 检查字符串是否值包含十进制字符,如果是返回True,否则返回False。
    • isdigit(): 如果字符串只包含数字则返回True,否则返回False。
    • isnumeric(): 如果字符串中只包含数字字符,则返回True,否则返回False。
    num = "1"  #unicode
    num.isdigit()   # True
    num.isdecimal() # True
    num.isnumeric() # True
    
    num = "1" # 全角
    num.isdigit()   # True
    num.isdecimal() # True
    num.isnumeric() # True
    
    num = b"1" # byte
    num.isdigit()   # True
    num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
    num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
    
    num = "IV" # 罗马数字
    num.isdigit()   # True
    num.isdecimal() # False
    num.isnumeric() # True
    
    num = "四" # 汉字
    num.isdigit()   # False
    num.isdecimal() # False
    num.isnumeric() # True
    
    ===================
    isdigit()
    True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
    False: 汉字数字
    Error: 无
    
    isdecimal()
    True: Unicode数字,全角数字(双字节)
    False: 罗马数字,汉字数字
    Error: byte数字(单字节)
    
    isnumeric()
    True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
    False: 无
    Error: byte数字(单字节)
    
    ================
    import unicodedata
    
    unicodedata.digit("2")   # 2
    unicodedata.decimal("2") # 2
    unicodedata.numeric("2") # 2.0
    
    unicodedata.digit("2")   # 2
    unicodedata.decimal("2") # 2
    unicodedata.numeric("2") # 2.0
    
    unicodedata.digit(b"3")   # TypeError: must be str, not bytes
    unicodedata.decimal(b"3") # TypeError: must be str, not bytes
    unicodedata.numeric(b"3") # TypeError: must be str, not bytes
    
    unicodedata.digit("Ⅷ")   # ValueError: not a digit
    unicodedata.decimal("Ⅷ") # ValueError: not a decimal
    unicodedata.numeric("Ⅷ") # 8.0
    
    unicodedata.digit("四")   # ValueError: not a digit
    unicodedata.decimal("四") # ValueError: not a decimal
    unicodedata.numeric("四") # 4.0
    
    #"〇","零","一","壱","二","弐","三","参","四","五","六","七","八","九","十","廿","卅","卌","百","千","万","万","亿"
    

    6.is其他

    • isalnum(): 如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False。
    • isalpha(): 如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。
    • islower(): 如果字符串中只包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False。
    • isspace(): 如果字符串中只包含空白,则返回True,否则返回False
    • isupper(): 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False。
    • istitle(): 如果字符串是标题类型的(见title()),则返回True,否则返回False。

    4.存一个值or多个值:一个值

    5.有序or无序:只要是有索引的,都是有序的,因此字符串是有序的。

    name = 'nick'
    print(f'first:{id(name)}')
    name = 'nick handsome'
    print(f'second:{id(name)}')
    first:4377100160
    second:4377841264
    

    6.可变or不可变:不可变数据类型

  • 相关阅读:
    C# 关键字 virtual、override和new的用法
    架构技术及架构要素总结【转】
    vue文件目录结构
    vue项目中,如何对static文件夹下的静态文件添加时间戳,以达到清除缓存
    webpack中关于require与import的区别
    vue 根据下拉框动态切换form的rule
    el-select 根据value查询其对应的label值
    web前端项目规范
    JavaScript 编码规范
    HTML 编码规范
  • 原文地址:https://www.cnblogs.com/SkyOceanchen/p/11270441.html
Copyright © 2020-2023  润新知