6 字符串

6.1 认识字符串

  • 字符串是 Python 中最常用的数据类型。我们一般使用引号来创建字符串。创建字符串很简单,只要为变量分配一个值即可
  • 一对引号字符串
      name1 = 'Tom'
      name2 = "Rose"
    
  • 三引号字符串串

      name3 = ''' Tom '''
      name4 = """ Rose """
      a = ''' i am Tom, 
              nice to meet you! '''
    
      b = """ i am Rose, 
              nice to meet you! """
    
    • 三引号形式的字符串支持换行
  • 思考:如果创建一个字符串I'm Tom?
      c = "I'm Tom"
      d = 'I\'m Tom'
    

6.2 字符串的输出

  • 格式化操作符

      name = '君哥'
      position = '讲师'
      address = '北京市'
    
      print('--------------------------------------------------')
      print("姓名:%s" % name)
      print("职位:%s" % position)
      print("公司地址:%s" % address)
      print('--------------------------------------------------')
    
  • f-strings
    • f-strings 提供一种简洁易读的方式, 可以在字符串中包含 Python 表达式. f-strings 以字母 'f' 或 'F' 为前缀, 格式化字符串使用一对单引号、双引号、三单引号、三双引号. 格式化字符串中
    name = '小明'
    age = 33
    format_string1 = f'我的名字是 {name}, 我的年龄是 {age}'
    format_string2 = f"我的名字是 {name}, 我的年龄是 {age}"
    format_string3 = F'''我的名字是 {name}, 我的年龄是 {age}'''
    format_string4 = F"""我的名字是 {name}, 我的年龄是 {age}"""
    format_string5 = f'3 + 5 = {3 + 5}'
    a = 10
    b = 20
    format_string6 = f'3 + 5 = {a + b}'

    print(format_string1)
    print(format_string2)
    print(format_string3)
    print(format_string4)
    print(format_string5)
    print(format_string6)

6.3 字符串的输入

  • 之前在学习input的时候,通过它能够完成从键盘获取数据,然后保存到指定的变量中
  • 注意:input获取的数据,都以字符串的方式进行保存,即使输入的是数字,那么也是以字符串方式保存

6.4 下标和切片

6.4.1 下标

  • 所谓“下标”,就是编号,就好比超市中的存储柜的编号,通过这个编号就能找到相应的存储空间,列表与元组支持下标索引好理解,字符串实际上就是字符的数组,所以也支持下标索引
  • 如果想取出部分字符,那么可以通过下标的方法,(注意python中下标从 0 开始)

      name = 'abcdef'
    
      print(name[0])
      print(name[1])
      print(name[2])
    

6.4.2 切片

  • 切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作
  • 切片的语法:[起始:结束:步长]
    • 注意:选取的区间从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身),步长表示选取间隔
    # 序列名[开始位置的下标:结束位置的下标:步长]

    str1 = '012345678'
    print(str1[2:5:1])  # 234
    print(str1[2:5:2])  # 24
    print(str1[2:5])  # 234
    print(str1[:5])  # 01234 -- 如果不写开始,默认从0开始选取
    print(str1[2:])  # 2345678 -- 如果不写结束,表示选取到最后
    print(str1[:])  # 012345678 -- 如果不写开始和结束,表示选取所有

    # 负数测试
    print(str1[::-1])  # 876543210 -- 如果步长为负数,表示倒叙选取
    print(str1[-4:-1])  # 567 -- 下标-1表示最后一个数据,依次向前类推

    # 终极测试
    print(str1[-4:-1:1])  # 567
    print(str1[-4:-1:-1])  # 不能选取出数据:从-4开始到-1结束,选取方向为从左到右,但是-1步长:从右向左选取
    # **** 如果选取方向(下标开始到结束的方向) 和 步长的方向冲突,则无法选取数据

    print(str1[-1:-4:-1])  # 876

6.5 字符串的操作

6.5.1 查找

  • mystr = "hello world and itcast and itheima and Python"
  • find
    • 作用:检测 str 是否包含在 mystr 中,如果是返回开始的索引值,否则返回-1
    • 语法:字符串序列.find(子串, 开始位置下标, 结束位置下标)
    • 示例:
        print(mystr.find('and'))  # 12
        print(mystr.find('and', 15, 30))  # 23
        print(mystr.find('ands'))  # -1 , ands子串不存在
      
  • rfind
    • 作用:类似于 find() 函数,不过是从右边开始查找
    • 语法:字符串序列.rfind(子串, 开始位置下标, 结束位置下标)
  • index
    • 作用:跟 find() 方法一样,只不过如果str不在 mystr中会报一个异常
    • 语法:字符串序列.index(子串, 开始位置下标, 结束位置下标)
    • 示例:
        print(mystr.index('and'))  # 12
        print(mystr.index('and', 15, 30))  # 23
        print(mystr.index('ands'))  # 如果index查找子串不存在,报错
      
  • rindex
    • 作用:类似于 index() 函数,不过是从右边开始查找
    • 语法:字符串序列.rindex(子串, 开始位置下标, 结束位置下标)
  • count
    • 作用:返回 str在start和end之间 在 mystr里面出现的次数
    • 语法:字符串序列.count(子串, 开始位置下标, 结束位置下标)
    • 示例:
        print(mystr.count('and', 15, 30)) # 1
        print(mystr.count('and'))  # 3
        print(mystr.count('ands'))  # 0
      

6.5.2 修改

  • mystr = "hello world and itcast and itheima and Python"
  • replace

    • 作用:把 mystr 中的 str1 替换成 str2 ,如果 count 指定,则替换不超过 count ,replace函数有返回值,返回值是修改后的字符串
    • 语法:字符串序列.replace(旧子串, 新子串, 替换次数)
    • 示例:

      new_str = mystr.replace('and', 'he') # hello world he itcast he itheima he Python
      new_str = mystr.replace('and', 'he', 1) # hello world he itcast and itheima and Python
      
      # 替换次数如果超出子串出现的次数,表示替换所有这个子串
      new_str = mystr.replace('and', 'he', 10) # hello world he itcast he itheima he Python
      print(mystr) # hello world and itcast and itheima and Python
      print(new_str)
      
  • split
    • 作用:以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串,返回一个列表, 丢失分割字符
    • 语法:字符串序列.split(分割字符, num)
    • 示例:
      list1 = mystr.split('and') # ['hello world ', ' itcast ', ' itheima ', ' Python']
      list1 = mystr.split('and', 2) # ['hello world ', ' itcast ', ' itheima and Python']
      print(list1)
      
  • splitlines
    • 作用:按照行分隔,返回一个包含各行作为元素的列表
    • 语法:字符串序列.splitlines()
  • partition
    • 作用:把mystr以str分割成三部分,str前,str和str后
    • 语法:字符串序列.partition(str)
  • rpartition
    • 作用:类似于 partition()函数,不过是从右边开始
    • 语法:字符串序列.rpartition(str)
  • join
    • 作用:mystr 中每个元素后面插入str,构造出一个新的字符串
    • 语法:字符或子串.join(多字符串组成的序列)
    • 示例:
        mylist = ['aa', 'bb', 'cc']
        str = ' '
        str1 = '_'
        new_str = str.join(mylist) # aa bb cc
        new_str1 = str1.join(mylist) # aa_bb_cc
        print(new_str)
        print(new_str1)
      
  • capitalize
    • 作用:字符串首字母大写
    • 语法:字符串序列.capitalize()
  • title
    • 作用:字符串中每个单词首字母大写
    • 语法:字符串序列.title()
  • upper
    • 作用:字符串内容全部小写转大写
    • 语法:字符串序列.upper()
  • lower
    • 作用:字符串内容全部大写转小写
    • 语法:字符串序列.lower()
  • lstrip
    • 作用:删除字符串左侧空白字符
    • 语法:字符串序列.lstrip()
  • rstrip
    • 作用:删除字符串右侧空白字符
    • 语法:字符串序列.rstrip()
  • strip
    • 作用:删除字符串两侧空白字符
    • 语法:字符串序列.strip()
  • ljust
    • 作用:返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
    • 语法:字符串序列.ljust(width)
  • rjust
    • 作用:返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
    • 语法:字符串序列.rjust(width)
  • center
    • 作用:返回一个原字符串居中对齐,并使用空格填充至长度 width 的新字符串
    • 语法:字符串序列.center(width)

6.5.3 判断

  • mystr = "hello world and itcast and itheima and Python"
  • startswith
    • 作用:检查字符串是否是以某个子串开头, 是则返回 True,否则返回 False
    • 语法:字符串序列.startswith(子串)
  • endswith
    • 作用:检查字符串是否是以某个子串结尾, 是则返回 True,否则返回 False
    • 语法:字符串序列.endswith(子串)
  • isalpha
    • 作用:如果 mystr 所有字符都是字母,是则返回 True,否则返回 False
    • 语法:字符串序列.isalpha()
  • isdigit
    • 作用:如果 mystr 所有字符都是数字,是则返回 True,否则返回 False
    • 语法:字符串序列.isdigit()
  • isalnum
    • 作用:如果 mystr 所有字符都是数字或字母,是则返回 True,否则返回 False
    • 语法:字符串序列.isalnum()
  • isspace
    • 作用:如果 mystr 所有字符都是空格,是则返回 True,否则返回 False
    • 语法:字符串序列.isspace()

results matching ""

    No results matching ""