day10-string

day10-string

01 字符编码

1,字符编码

为了能够让计算机存储文字符号,给每个符号对应了一个固定的数字,每次在需要存储的时候,就去存这个固定的数字。
每个对应的那个数字就是这个符号的编码值。
pillow(PIL) 处理图片的对应编码

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

(1) ASCII码表
美国信息码(只包含了美国人常用的符号,总共128个)
数字字符
大写字母 (A - 65)
小写字母 (a - 97)
英文输入法下的特殊符号
(2) Unicode编码表(Python) - 包含了世界上所有的国家所有的民族的所有的语言符号
Unicode编码表包含了ASSCII (前128个字符就是ASCII码表中的内容)
中文编码范围:4e00 ~ 9fa5 (0x9fa5-0x4e00= 2w+)

3.编码值的应用

(1) chr(编码值) - 获取编码值对应的字符

print(chr(97))      # 'a'
print(chr(0x4e00))  # '一'
print(chr(0x9fa5))  # 龥

# from pypinyin import pinyin
# print(pinyin('龥')

# from pypinyin import pinyin
# for x in range(0x4e00, 0x9fa5+1):
# #    print(chr(x), pinyin(chr(x)), end=" ")
#      print(chr(x), end=" ")

(2) ord(字符) - 获取指定字符对应的编码值
注意:字符值得是长度为1的字符串 返回的十进制

print(ord('a'))      # 97
print(ord('余'))     # 20313

# 案例:将char对应的小写字母转换成大写字母
char = 'm'
# m -> M
print(chr(ord(char)-32))

(3) 编码字符:\u4位的16进制编码值
在字符传中提供字符的方式有两种:a.直接提供字符 b.使用编码字符
hex(10进制数) - 获取指定数字对应的16进制表示方式

str1 = "ab你好"
print(str1)

# 如果知道字符编码是多少,但是不知道字符是什么的时候,就可以使用编码字符来表示这个字符
str2 = "\u0061\u9fa5"
print(str2)

char = 'j'
if '一' <= char <= '\u9fa5':        #if '一' <= char <= '龥':
     print(char,'是中文字符')
else:
     print(char, '不是中文字符')

02 字符串取操作

1.获取的单个字符

字符串[下标]
注意:转义的长度是1 如:\n -> 长度为1

str1 = '\thello\nworld!\u9fa5'
print(str1[5])      # o
print(str1[-1])     # 龥
2.字符串切片

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

str1 = 'good good study!'
print(str1[1:-2:2])    # odgo td
print(str1[-3:])      # dy!
3.遍历字符串
for i in str1:
    print(i, end='')
print("")

for index in range(len(str1)):
    print(index, str1[index],end="、")
print("")

for index, item in enumerate(str1):
    print(index, item, end=",")
print("")

03字符串相关操作

1.字符串加法运算 - 字符产拼接

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

str1 = 'hello'
str2 = 'world'
print(str1 + str2)           # helloworld
print(str1 + ' ' + str2)     # hello world
print("------------------------1---------------------")

# 案例:提取自付出中所有数字字符
str1 = '世界上89kl22.9;;//sh66-=1'
# '89889661'
new_str1 = ''
for i in str1:
    if '0' <= i <= '9':
        new_str1 += i
print(new_str1)        # '89889661'
print("------------------------1.案例1---------------------")

# 案例2:在每一个数字字符后面插入一个 %
str1 = '世界上89kl22.9;;//sh66-=1'
new_str1 = ''
for i in str1:
    if '0' <= i <= '9':
        new_str1 += i + '%'
    else:
        new_str1 += i
print(new_str1)     # 世界上8%9%kl2%2%.9%;;//sh6%6%-=1%
print("------------------------1.案例2---------------------")

# 练习:将字符串中所有的数字字符都改成 +
str1 = '世界上89kl22.9;;//sh66-=1'
new_str1 = ''
for i in str1:
    if '0' <= i <= '9':
        new_str1 += "+"
    else:
        new_str1 += i
print(new_str1)        # 世界上++kl++.+;;//sh++-=+
2.字符串乘法运算

字符串 * N、N * 字符串 - 瓤子付出啊中元素重复N次产生一个新的字符串

str1 = 'a' * 10
print(str1)        # aaaaaaaaaa

str1 = '你好' * 5
print(str1)         # 你好你好你好你好你好
3.字符串比较运算

(1) 比较是否相等: ==、!=

print('abc' == 'bac')    # False

(2) 比较大小
两个自付出比较大小、比较是第一对不相等的字符的编码值的大小

判断字符的性质:
是否是数字字符:'0' <= x <= '9'
是否是小写字母:'a' <= x <= 'z'
是否是大写字母:'A' <= x <= 'Z'
是否是字母:'a' <= x <= 'z' or 'A' <= x <= 'Z'
是否是中文:'\u4e00' <= x <= '\u9fa5'
print('abc' > 'bcc')      # 'a' > 'b'    False
print('a1mn' > 'abc')     # '1' > 'b'    False
print('a你好' > 'abc')     # '你' > 'b'   True
4.in 和 not in

字符串1 in 字符串2 - 字符串1是否是字符串2的子串(字符串2是否包含字符串1)

print('a' in 'abc')            # True
print('ab' in 'abc')           # True
print('ac' in 'abc')           # False

print(10 in [10, 20, 30])         # True
print([10, 20] in [10, 20, 30])    # False

5.相关函数
(1) max、min、sorted 排序结果为列表

print(max('helloworld'))      # 'w'
print(sorted('helloworld'))   # ['d', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

(2) len(字符串)

msg = '\thello\nworld!\u4e00'
print(len(msg))

(3) str(数据) - 任何类型的数据都可以转换成字符串;转换的时候是在数据的打印值外面加引号

print(str(100))    # '100'
str(1.23)    # '1.23'
str(True)    # 'True'

list1 = [10, 20, 30, 40]
str(list1)     # '[10, 20, 30, 40]'

list1 = [10,20,30,40]
print(list1)    # [10, 20, 30, 40]
str(list1)      # '[10, 20, 30, 40]'

list1 = ["余婷",18]
print(list1)
str(list1)

(4) eval(字符串) - 去掉字符串的引号,获取引号中表达式的结果

a = eval('100')          # 100
b = eval('1.23')           # 1.23
# c = eval('abc')       # 报错!

abc = 100
c1 = 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)
print("-----------------------------------------------------------")
msg = 'print(100)'
eval(msg)

a1 = int(input('请输入数字a的值:'))
b1 = int(input('请输入数字b的值:'))
value = input('请选择运算符(+、-、*、/):')
result = eval('a' + value + 'b')    # 'a+b'、'a-b'
print(result)

04 字符串相关方法

字符串.xxx()

1.字符串.join() - 将序列中的元素用指定的字符串连接成一个新的字符串(序列中的元素必须全部都是字符串)
list1 = ['小明', '张三', '李四', '王五']

result = "+".join(list1)
print(result)    #
print("-1---------------")

result = 'and'.join(list1)
print(result)
print("-2---------------")

result = "**".join('abc')
print(result)
print("-3---------------")

nums = [90, 78, 67, 45, 23]  # ['90', '78',.....]
result = "+".join([str(x) for x in nums])
print(result)   # 90 + 78 + 67 + 45 + 23
print(eval(result))   # 303
2.字符串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
3.

(1) 字符串1.split(字符串2) - 将字符串1中所有的字符串2作为切割点对字符串1进行切割
(2) 字符串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?']

date = '2020/6/5'
print(date.split('/'))     # ['2020', '6', '5']

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

(1) 符串1.replace(字符串2, 字符串3) - 将字符串1中所有的字符串2都替换成字符串3
(2) 符串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 ?

msg = 'how are you? i am fine! thank you, and you?'
result = msg.replace('you', '+', 2)
print(result)    # how are +? i am fine! thank +, and you?
5.字符串.strip() - 去掉字符串前后的空白字符
msg = """              msg = 'how are you? i am fine! thank you, and you?'
"""
print(msg)          #         msg = 'how are you? i am fine! thank you, and you?'
print(msg.strip())    # msg = 'how are you? i am fine! thank you, and you?'

msg = '小/明///'
print(msg.strip('/'))
6.

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

print('JSKS'.isupper())
print('A'.isupper())
7.字符串.islower() - 判断字符或者字符串是否全是小写字母
print('a'.islower())        # True
8.字符串.isdigit() - 判断字符或者字符串是否全是数字字符
print('9'.isdigit())
print('720233'.isdigit())
9.字符串.upper()
print('hs技术上223jKJ90lo'.upper())
print('m'.upper())
10.字符串.lower()
print('hAMs技术上223jKJ90lo'.lower())
print('Q'.lower())
print("-------------------------------10-------------------------------")

# 案例:判断char是否是字母
char = '2'

if char.islower() or char.isupper():
    print('是字母')
else:
    print('不是字母')


if 'a' <= char <= 'z' or 'A' <= char <= 'Z':
    print('是字母')
else:
    print('不是字母')

05格式化字符串

解决的问题:字符串内容不确定
xxx今年xx岁,月薪:xxxx.xx元!

# name = input('请输入学生的名字:')
name = '张三'
# age = int(input('请输入学生的年龄:'))
age = 30
# money = float(input('请输入你的月薪:'))
money = 12000
1.字符串拼接
msg = name + '今年' + str(age) + '岁,月薪:' + str(money) + '元!'
print(msg)
2.格式字符串 - 包含格式占位符的字符串

(1) 语法:包含格式占位符的字符串 % (数据1, 数据2, 数据3,…)
(2) 注意:()中的数据必须和前面字符串中的占位符一一对应
(3) 常见的格式占位符:
%s - 可以给任何类型的数据占位
%d - 可以给任何数字占位(整数占位符,如果给的数字是小数,会自动转换成整数在拼接到字符串中)
%f - 可以给任何数字占位(浮点数占位符)
%.Nf - (控制保留N位小数 - 默认是保留6位小数)

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

result = 'x: %s' % 3.1455
print(result)
3.f-string

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

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

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


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

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

# {表达式:,.Nf}  -  标准的金额拼接
# 357800  -> ¥356,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、付费专栏及课程。

余额充值