day10-字符串

1. 字符串编码

1.1 字符编码

为了能够让计算机存储文字符号,给每个符号对应了一个固定的数字,每次需要存储这个符号的时候就存储这个固定的数字,每个对应的那个数字就是这个符号的编码值

1.2 编码表

保存字符和字符对应编码值的表

  1. ASCII码表

    美国信息码(只包含美国人常用的符号,总共128个)

    数字字符

    大写字母(A - 65)

    小写字母(a - 97)

    英文输入法下的特殊符号

  2. Unicode编码表(Python)

    包含了世界上所有的国家所有的民族所有的语言符号

    Unicode编码表包含了ASCII(前128个字符就是ASCII码表中的内容)

    中文编码范围:4e00 ~ 9fa5

1.3 编码值的应用
  1. chr(编码值):获取编码值对应的字符

    print(chr(0x4e00))      # '一'
    print(chr(0x9fa5))      # '龥'
    print(chr(97))          # 'a'
    
    from pypinyin import pinyin
    print(pinyin('龥'))
    
  2. ord(字符):获取指定字符对应的编码值

    # 注意:字符指的是长度为1的字符串
    print(ord('a'))         # 97
    print(ord('冉'))        # 20873
    
    # 案例:将char对应的小写字母转换成大写字母
    char = 'a'
    print(chr(ord(char) - 32))
    '''
    a:97        A:65
    b:98        B:66
    c:99        C:67
    '''
    
  3. 编码字符:\u 4位的16进制编码值

    在字符串提供字符的方式有两种:

    ​ a. 直接提供字符

    ​ b. 使用编码字符

    # hex(10进制数) - 获取指定数字对应的16进制表示方式
    str1 = 'ab你好'
    print(str1)
    
    # 如果知道字符编码值是多少,但是不知道字符是什么时候,就可以使用编码字符来表示这个字符
    str2 = '\u0061\u9fa5'
    print(str2)
    
    char = 'j'
    if '\u4e00' <= char <= '\u9fa5':
        print(char, '是中文字符')
    else:
        print(char, '不是中文字符')
    

2. 获取字符

2.1 获取单个字符

字符串[下标]

注意:转义的长度是1

str1 = '\thello\nworld\u9fa5'
print(str1[5])
print(str1[-1])
2.2 字符串切片

字符串[开始下标:结束下标:步长]

str2 = 'good good study!'
print(str2[1:-2:2])         # 'odgo td'
print(str2[-3:])            # 'dy!'
2.3 遍历字符串
for i in str2:
    print(i)

for index in range(len(str2)):
    print(index, str2[index])

for index, item in enumerate(str2):
    print(index, item)

3. 字符串相关操作

3.1 字符串加法运算

字符串1 + 字符串2:将两个字符串合并成一个字符串

str1 = 'hello'
str2 = '你好'
print(str1 + str2)
print(str1 + ' ' + str2)

# 案例:提取字符串中所有数字字符
str3 = '5er8448et6e6f84'
new_str = ''
for i in str3:
    if '0' <= i <= '9':
        new_str += i
print(new_str)

# 案例:在每一个数字字符后面插入一个%
new_str = ''
for i in str3:
    if '0' <= i <= '9':
        new_str += i + '%'
    else:
        new_str += i
print(new_str)

# 练习:将字符串中所有的数字字符改成+
new_str = ''
for i in str3:
    if '0' <= i <= '9':
        new_str += '+'
    else:
        new_str += i
print(str3)
print(new_str)
3.2 字符串乘法运算

字符串 * N、N * 字符串:让字符串中元素重复N次产生一个新的字符串

str1 = 'a' * 10
print(str1)

str2 = '你好' * 10
print(str2)
3.3 字符串比较运算
  1. 比较是否相等:==、!=

    print('abc' == 'cba')       # False
    
  2. 比较大小

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

    判断字符的性质:

    ​ 是否是数字字符:‘0’ <= x <= ‘9’

    ​ 是否是小写字母:‘a’ <= x <= ‘z’

    ​ 是否是大写字母:‘A’ <= x <= ‘Z’

    ​ 是否是字母:‘a’ <= x <= ‘z’ or ‘A’ <= x <= ‘Z’

    ​ 是否是中文:‘\u4e00’ <= x <= ‘\u9fa5’

    print('abc' > 'bbc')        # ’a' > 'b' False
    print('a1bc' > 'abc')       # '1' > 'a' False
    print('a你好' > 'abc')      # '你好' > 'b' True
    
3.4 in 和 not in
print('a' in 'abc')
3.5 相关函数
  1. maxminsorted

    print(max('helloworld'))    # 'w'
    print(sorted('helloworld')) # ['d', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
    
  2. len(字符串)

    msg = '\thello\nworld\u9fa5'
    print(len((msg)))
    
  3. str(数据)

    任何数据都可以转换成字符串;转换的时候是在数据的打印值外面加引号

    str(100)        # '100'
    str(1.23)       # ’1.23‘
    
    list1 = [10, 20, 30, 40]
    a = str(list1)      # '[10, 20, 30, 40]'
    print(len((a)))
    
    list1 = [10,20,30,40]
    str(list1)          # '[10, 20, 30, 40]'
    
    list1 = ["方法",18,'拿']
    print(list1)        # '['方法', 18, '拿']'
    str(list1)          # "['方法', 18, '拿']"
    
  4. eval(字符串)

    去掉字符串的引号,获取引号表达式的结果

    a = eval('100')         # a = 100
    b = eval('1.23')        # b = 1.23
    
    abc = 100
    c = eval('abc')         # c = abc
    
    d = eval('"hello"')     # d = "hello"
    
    a1 = eval('[10, 20, 30, 40]')       # a1 = [10, 20, 30, 40]
    print(a1)
    a1.append(100)
    print(a1)               # [10, 20, 30, 40, 100]
    
    b1 = eval('10, 20')     # b1 = 10 + 20
    print(b1)
    
    msg = 'print(100)'
    eval(msg)
    
    a1 = int(input('请输入a的值:'))
    b1 = int(input('请输入b的值:'))
    value = input('请输入运算符:')
    result = eval(f'a1{value}b1')
    print(result)
    

4. 字符串相关方法

4.1 join()

字符串.join():将序列中的元素用指定的字符串连接成一个新的字符串(序列中的元素必须全部是字符串)

list1 = ['张三', '李四', '王五']

result = '+'.join(list1)
print(result)           # '张三+李四+王五'

result = ' and '.join(list1)
print(result)           # 张三 and 李四 and 王五

result = '**'.join('abc')
print(result)           # a**b**c

nums = [90, 87, 85, 78, 32]
result = '+'.join([str(x) for x in nums])
print(result)           # '90+87+85+78+32'
print(eval(result))     # 372
4.2 count()

字符串1.count(字符串2):条件字符串1中字符串2的个数

msg = 'how are you? i am fine! thank you, and you?'

result = msg.count('a')
print(result)           # '4'

print(msg.count('you'))  # '3'
4.3 split()

字符串1.split(字符串2):将字符串1中所有的字符串2作为切割点对字符串1进行切割

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

msg = 'how are you? i am fine! thank you, and you?'
result = msg.split('you')
print(result)           # '['how are ', '? i am fine! thank ', ', and ', '?']'

result = msg.split(' ')
print(result)           # '['how', 'are', 'you?', 'i', 'am', 'fine!', 'thank', 'you,', 'and', 'you?']'

result = msg.split(' ', 3)
print(result)           # '['how', 'are', 'you?', 'i am fine! thank you, and you?']'
4.4 replace()

字符串1.replace(字符串2, 字符串3):将字符串1中所有的字符串2都替换成字符串3

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

msg = 'how are you? i am fine! thank you, and you?'
result = msg.replace('you', 'me')
print(result)           # 'how are me? i am fine! thank me, and me?'

result = msg.replace('you', '')
print(result)           # 'how are ? i am fine! thank , and ?'

result = msg.replace('you', '+', 2)
print(result)           # 'how are +? i am fine! thank +, and you?'
4.5 strip()

字符串.strip():去掉字符串前后的空白字符

msg = '''

   how are you? i am fine!
thank you, and you?

'''
print(msg.strip())

name = '小/明//'
print(name.strip('/'))
4.6 isupper()

字符串.isupper():判断字符串是否是纯大写字母字符串
字符.isupper():判断字符是否是大写字母

print('KJF'.isupper())
4.7 islower()

字符串.islower():判断字符串是否是纯小写字母字符串

print('a'.islower())
4.8 isdigit()

字符串.isdigit():判断字符串是否是纯数字字符串

print('55661'.isdigit())
4.9 upper()

字符串.upper()

print('kjsn就会发生fs'.upper())
print('m'.upper())
4.10 lower()

字符串.lower()

print('KJSN就会发生FS'.lower())
print('M'.lower())

# 案例:判断char是否是字母
char = 's'
if char.isupper() or char.islower():
    print('是字母')
else:
    print('不是字母')

5. 格式字符串

# 解决的问题:字符串不确定
# name = input('请输入学生的名字:')
# age = int(input('请输入学生的年龄:'))
# money = float(input('请输入薪水'))
name = '张三'
age = 18
money = 364826.0

# xxx今年xx岁,月薪:xxx元
5.1 字符串拼接
msg = name + '今年' + str(age) + '岁,月薪:' + str(money) + '元!'
print(msg)
5.2 格式字符串

包含格式占位符的字符串

  1. 语法:包含格式占位符的字符串 %(数据1, 数据2, 数据3, …)

  2. 注意:()中的数据必须和前面字符串中的占位符一一对应

  3. 常见的格式占位符

    %s:可以给任何类型的数据占位

    %d:可以给任何数字占位(整数占位符,如果给的数字是小数,会自动转换成整数再拼接 到字符串中)

    %f:可以给任何数字占位(浮点数占位符)

    %.Nf:控制保留N位小数,默认保留6位小数

msg = '%s今年%s岁,月薪:%s元!' % (name, age, money)
print(msg)

result = 'x: %s' % 100
print(result)
5.3 f字符串

在字符串引号的前面加f,就可以在字符串中通过{表达式}中表达式的结果来给字符串提供内容

msg = f'{name}今年{age}岁,月薪:{money}元!'
print(msg)

a = 20
b = 100
print(f'{a} + {b} = {a+b}')     # 20 + 100 = 120

# {表达式:.Nf} - 控制小数保留N位小数
a = 1.23
b = 2.3
print(f'{a:.2f} + {b:.2f} = {a+b:.0f}')

# {表达式:.N%} - 控制数字显示成百分比,N空值百分比的小数位数
c = 0.98
print(f'及格率:{c:.0%}')

# {表达式:,.Nf} - 标准的金额拼接
# 357800 -> 357,800.00
d = 3578000
print(f'¥{d:,.2f}')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值