day8-字符串

字符串和字符

1. 什么是字符串(str)

  • “”"
    容器;将’’、""、’’’’’’、"""""“作为容器的表示,里面的每个独立的文字信息就是它的元素(引号中的每个符号都是字符串的元素)
    元素:引号中的每个符号都是元素, 字符串的元素又叫字符
    不可变(不支持增删改);有序的(支持下标操作)
    “””

    s1 = 'a6,你好'
    s2 = "数ks022123"
    s3 = '❀♥🌹'
    print(type(s1), type(s2), type(s3))    # <class 'str'> <class 'str'> <class 'str'>
    s4 = '''abc'''
    s5 = """abc123"""
    print(type(s4), type(s5))   # <class 'str'> <class 'str'>
    
    s6 = 'abc123'
    print(s6)
    
  • ‘’'和"""对应的字符串可以在内容中直接通过回车换行

    s7 = '''abc
    123
    你好吗?'''
    print(s7)
    

2. 字符

  • python中只有字符的概念,没有对应的数据类型。如果需要字符用长度是1的字符串来表示

  • 1)转义字符

  • 字符串中的元素/符号/字符分为两种:有一种是普通字符,另外一种是转义字符

  • a.普通字符 - 除了转义字符以外的字符都属于普通字符;普通字符在字符串中表示这个符号本身

  • b.转义字符 - 通过 \加其他字符 的形式存在, 它在字符串中有特殊功能或者特殊意义

  • \n - 换行(相当于按一下回车)

  • \t - 水平制表符(相当于按一下tab键)

  • ’ - 表示一个单引号

  • " - 表示一个双引号

  • \ - 表示一个反斜杠

  • u四位的16进制数 - 表示四位16进制数作为编码值对应的字符(编码字符)

    s8 = '\tabc\n123'
    print(s8)
    
    s9 = 'abc\'123'
    print(s9)
    
    s10 = "abc'123"
    print(s10)
    
    s11 = "abc\"123"
    print(s11)
    s12 = 'abc\"123'
    print(s12)
    
    s13 = 'abc\\n123'
    print(s13)   # abc\n123
    
    s14 = 'abc\u4eff123'
    print(s14)   # abc仿123
    

3.字符编码

  • “”"
    1)计算机能直接存储的数据只有数字,而且存的是数字的补码。
    2)文本数据没有办法直接存到计算中,计算在保存文本数据的时候,存的其实是每个文本符号对应的数字
    (对计算机来讲,每个文本符号都会对应一个固定的数字),每一个文本符号对应的数字就是这个符号的编码值
    3)字符编码表:ASCII码表、Unicode编码表
    编码表中保存的就是每个符号和数字之间的一一对应关系
    ASCII码表: a.总共128个字符,每个字符对应你的编码范围:0~127 (只有美国人用的符号)
    b. 数字在字母的前面;大写字母在小写字母前面;大写字母和小写字母没有紧挨着
    Unicode编码表:a.Unicode编码表示ASCII码表的扩展
    b.中文编码范围:4e00 ~ 9fa5
    c.python采用的Unicode编码表
    “”"

4.编码值的使用

  • 1)编码字符: \u编码值

    print('\u4e00~\u9fa5')   # 一~龥
    print('a\u0061')    # aa  -> 61是a的16进制编码值
    print('\u096f\u097f')     # ९ॿ
    print('\u1100\u114f')     # ᄀᅏ
    
  • 2)chr(编码值) - 获取指定编码值对应的字符

    print(chr(0x4e00))   # 一
    print(chr(97))     # a
    print(chr(0x56ef))   # 囯
    
    for x in range(0x1800, 0x18AF+1):
        print(chr(x), end=' ')
    
    print(len(range(0x4e00, 0x9fa5+1)))
    
  • 3)ord(字符) - 获取字符编码值

    print(ord('袁'), ord('华'), ord('涛'))  # 34945 21326 28059
    print(hex(ord('袁')), hex(ord('华')), hex(ord('涛')))   # 0x8881 0x534e 0x6d9b
    

获取字符

1.获取字符

  • 1)获取单个字符

  • 字符串[下标]

    str1 = 'hello python!'
    print(str1[1], str1[-1])
    
  • a.一个空格是一个字符

    str2 = 'abc 123'
    print(str2[4])    # 1
    
    str3 = 'abc  123'
    print(str3[5])    # 1
    
  • b.一个转义字符是一个字符(一个转义字符的长度是1)

    str4 = 'abc\n123'
    print(str4[4])    # 1
    
    str5 = '\tabc123'
    print(str5[1])   # a
    
    str6 = '    abc123'
    print(str6[4])   # a
    
    str7 = '\u4e00abc'
    print(str7[1])    # a
    
    1. 切片
    message = 'Really get to know yourself before you make any decision.'
    print(message[-5:])   # 'sion.'
    print(message[1:6:2])  # 'ely'
    print(message[::-1])
    print(message[:-5:-1])  # .noi
    
  • 3)遍历

    for x in 'ab\u4e00c':
        print(x)
    
    for index in range(len(message)):
        print('字符:', message[index])
    
    for index, item in enumerate(message):
        print(index, item)
    

字符串相关操作

1.数学运算符: +, *

  • 1)字符串1 + 字符串2 - 将两个字符串合并产生一个新的字符串

    str1 = 'abc'
    str2 = '123'
    print(str1 + str2)   # 'abc123'
    
    name = '张三'
    age = 18
    # xxx今年xx岁!
    message = name+'今年'+str(age)+'岁!'
    print(message)
    
  • 2)字符串N / N字符串 - 字符串重复N次产生一个新的字符串

    print('abc'*2)
    print('hello world!\n' * 10)
    

2.比较运算符

  • 1)==、!=

    print('abc' == 'abc')   # age
    print('abc' == 'acb')   # False
    
  • 2)>、<、>=、<=

  • 字符串1 > 字符串2

  • 两个字符串比较大小,比较的是第一对不相等的字符的大小。(两个字符比较大小比较的是字符的编码值的大小)

    print('abc' > '123456')   # True
    print('Abc' > 'abc')     # False
    print('余婷' > 'hello world!')   # True
    
  • 比较运算符的应用:判断字符的类型

  • “”"
    是否是数字: 48 <= ord(字符) <= 57 / ‘0’ <= 字符 <= ‘9’
    是否是大写字母: ‘A’ <= 字符 <= ‘Z’
    是否是小写字母: ‘a’ <= 字符 <= ‘z’
    是否是字母:‘A’ <= 字符 <= ‘Z’ or ‘a’ <= 字符 <= ‘z’
    是否是中文:’\u4e00’ <= 字符 <= ‘\u9fa5’
    “”"

  • 练习1:分别统计字符串中中文字符的个数和字母的个数

    str3 = 'hsjj数据是2823竭尽所能SJJ==-2...数kkl'
    count1 = 0
    count2 = 0
    for x in str3:
        if '\u4e00' <= x <= '\u9fa5':
            count1 += 1
        elif 'A' <= x <= 'Z' or 'a' <= x <= 'z':
            count2 += 1
    print('中文:', count1, '字母:', count2)
    
  • 练习2:判断一个字符串中是否有数字字符,有打印True, 没有打印False

  • ‘bans江苏省’ -> False ‘三角函数sss223==’ -> True

    str4 = 'bans江苏省'
    for x in str4:
        if '0' <= x <= '9':
            print(True)
            break
    else:
        print(False)
    

3. in 和 not in

  • 字符 in 字符串 - 判断字符串中是否存在指定的字符

  • 字符串1 in 字符串2 - 判断字符串1是否是字符串2的子串

    print('a' in 'abc')   # True
    print('Z' in 'abc')   # False
    
    print('abc' in 'a1b2c3')   # False
    print('abc' in '123abc舒克舒克')  # True
    

4.相关函数

  • max, min, sorted

    print(max('jskm'))
    print(sorted('jskm'))  # ['j', 'k', 'm', 's']
    
  • len

    print(len('abc'))    # 3
    print(len('\tabc\n123'))   # 8
    
  • str

  • str(数据) - 将数据转换成字符串

  • 所有类型数据都可以转换成字符串;数据转换成字符串的时候,是直接在数据打印值最外层加引号

  • 100 -> ‘100’

  • 12.5 -> ‘12.5’

  • [10, 20, 30] -> ‘[10, 20, 30]’

  • [‘abc’, 10, 20] -> "[‘abc’, 10, 20] "

  • {‘name’: ‘张三’, ‘age’: 18} -> “{‘name’: ‘张三’, ‘age’: 18}”

    list1 = ['abc', 10, 20]
    list1_str = str(list1)
    print(list1_str)    # '['abc', 10, 20]'
    list2 = list(list1_str)
    print(list2)   # ['[', "'", 'a', 'b', 'c', "'", ',', ' ', '1', '0', ',', ' ', '2', '0', ']']
    
  • eval函数 - 将列表格式的字符串转换成列表或者将字典格式的字符串转换成字典…

    str5 = "['abc', 10, 20] "
    list2 = eval(str5)
    print(list2, type(list2))  # ['abc', 10, 20] <class 'list'>
    print(list2[0])
    
    dict1 = eval("{'name': '张三', 'age': 18}")
    print(dict1, type(dict1))   # {'name': '张三', 'age': 18} <class 'dict'>
    
    tuple1 = eval('(10, 20, 30)')
    print(tuple1, type(tuple1))   # (10, 20, 30) <class 'tuple'>
    
    result = eval('[10, "abc", 123]')
    print(result, type(result))     # [10, 'abc', 123] <class 'list'>
    

字符串相关方法

1.字符串1.count(字符串2) - 统计字符串2在字符串1中出现的次数

str1 = 'abmsidssasiissddd'
print(str1.count('a'))  # 2
print(str1.count('ss'))     # 2
print('how are you! and you?'.count('you'))   # 2

2.字符串1.index(字符串2) - 查找字符串2第一次出现在字符串1中的位置,以正的下标值返回

message = 'how are you! and you? and'
print(message.index('y'))    # 8
print(message.index('and'))  # 13
# print(message.index('anm'))    # ValueError: substring not found

3.字符串.join(序列) - 将序列中的元素通过字符串连接产生一个新的字符串

  • 注意:序列中的元素必须是字符串

    list1 = ['how', 'are', 'you']
    print(str(list1))   # "['how', 'are', 'you']"
    
    result = ''.join(list1)
    print(result)   # howareyou
    
    result = ' '.join(list1)
    print(result)   # how are you
    
    result = '加上'.join(list1)
    print(result)   # how加上are加上you
    
    result = '+'.join('abc')
    print(result)    # a+b+c
    
  • 练习:[‘abc’, 120, True, 12.5] -> ‘abc+120+True+12.5’

  • 先[‘abc’, 120, True, 12.5] -> [‘abc’, ‘120’, ‘True’, ‘12.5’]

    list1 = ['abc', 120, True, 12.5]
    print('+'.join([str(x) for x in list1]))   # abc+120+True+12.5
    
    new_list1 = []
    for x in list1:
        new_list1.append(str(x))
    print('+'.join(new_list1))  # abc+120+True+12.5
    

4.字符串1.split(字符串2) - 将字符串1中所有的字符串2作为切割点对字符串进行切割,返回切完后每一段对应的列表

字符串1.split(字符串2, N) - 将字符串1中前N个字符串2作为切割点

message = 'how are you!'
result = message.split(' ')
print(result)   # ['how', 'are', 'you!']

print('000abc123abc456abc789'.split('abc'))   # ['000', '123', '456', '789']
print('000abc123abc456abc789'.split('abc',2))   # ['000', '123', '456abc789']
print('000abc123abc456abc789'.split('abc',1))  # ['000', '123abc456abc789']
# 注意:切割点在字符串两端或者切割点连续出现都可能产生空串
print('abc123abc456abc789'.split('abc'))    # ['', '123', '456', '789']
print('123abcabc345'.split('abc'))   # ['123', '', '345']

list2 = ['', '123', '456', '', '789', '']
new_list2 = [x for x in list2 if x]
print(new_list2)    # ['123', '456', '789']
  • 注意:切割点在字符串两端或者切割点连续出现都可能产生空串

5.字符串1.replace(字符串2, 字符串3) - 将字符串1中的字符串2都替换成字符串3

字符串1.replace(字符串2, 字符串3, N) - 将字符串1中前N个字符串2替换成字符串3

str2 = 'abc123andyou'
print(str2.replace('a', 'B'))   # Bbc123Bndyou
print(str2.replace('a','B',1))  # Bbc123andyou
print(str2.replace('123', '321'))  # abc321andyou
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值