day10 - 字符串
一、09作业修改
2、获取列表中出现次数最多的元素
例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3
nums = [1,2,2,1,3] --> 打印1、2
max_count = 0
nums = [1, 2, 2, 1, 3]
# 1.去重
new_nums =list (set(nums))
# 每个元素出现次数
counts = []
for i in new_nums:
counts.append(nums.count(i))
print(counts)
# 获取最大次数
max_count=max(counts)
print('获取最大次数',max_count)
# 获取最大次数对应元素
for i in range(len(counts)):
if counts[i]==max_count:
print(new_nums[i])
# 方法2:数字作为键,次数作为值
counts={}
for i in nums:
count=counts.get(i,0)
counts[i]=count+1
max_count=0
items=[]
for x in counts:
if counts[x]>max_count:
items.clear()
items.append(x)
max_count=counts[x]
elif max_count==counts[x]:
items.append(x)
3、实现给定一个日期,判断这个日期是今年第几天的程序(尝试)
例如:2022/12/31 --> 今年第365天;2022/1/1 --> 今年第1天
date = input("输入日期以\间隔年月日:")
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:])
print(year, month, day)
sumday = 0
days1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31, ]
if (year % 400 == 0) or (year % 4 == 0 and not year % 100 == 0):
days1[1] = days1[1] + 1
sumday=0
sumday=sum(days1[:month-1])+day
print('今年第1天:', sumday)
二、字符编码
- 为了让计算机存储文字符号,给每个符号对应了一个固定的数字,在需要存储这个符号的时候,就去存储这个固定的数字。
- 每个对应的数字就是这个符号的编码值
1、编码表
1)ASCII码表 - 美国信息码(只包含了美国人常用的符号一共128个,2^7)
- 数字字符
- 大写字母65-A
- 小写字母97-a
- 英文输入法下的特殊符号
**2)Unicode编码表(python)**统一码(万国码):
- 包含了世界上所有国家所有民族的语言符号
- Unicode编码表包含ASCII码表(前128个字符就是ASCII码表中的内容)
- 中文编码范围:4e00~9fa5
2、使用编码值
1)chr(编码值) - 获取编码值对应的字符
print(chr(97)) # a
print(chr(0x4e00)) # 一
print(chr(0x9fa5)) # 龥
获取某种字符
print('________________________________________________________________________')
for i in range(0x0f00,0x0fff+1):
print(chr(i),end=' ')
print('________________________________________________________________________')
for i in range(0x2800,0x28ff+1):
print(chr(i),end=' ')
2)ord(字符) - 获取指定字符对应的编码值
- 注意:字符指的是长度为1的字符串
print(ord('a')) # 97
print(ord('李')) # 26446
print(ord('敏')) # 25935
案例:将char对应的小写字母转换成大写字母
char='u'
print(chr(ord(char)-32)) # U
char='D'
print(chr(ord(char)+32)) # d
3)编码字符:\u4位的十六进制编码值
- 在字符串中提供字符的方式:直接提供字符、使用编码字符
- hex(十进制数) - 获取指定数对应的十六进制数
- 如果知道字符编码是多少,但是不知道字符是什么,就可以使用编码字符来表示这个字符
str1='a'
str2='\u0061\u9fa5'
print(str2) # a龥
char='西'
if '\u4e00'<=char<='\u9fa5':
print(char,'是中文字符')
else:
print(char, '不是中文字符') # 西 是中文字符
三、字符相关操作
1、字符加法运算
1)字符串1+字符串2 - 将两个字符串合并成一个字符串
str1 = 'hellow'
str2 = '你好'
print(str1 + ' ' + str2)
**2)案例:**提取字符串中所有的数字字符
new_str1 = ''
str2 = 'ds1k3k456//45ka'
for i in str2:
if '0' <= i <= '9':
new_str1 += i
print(new_str1) # 1345645
**3)案例:**在每一个数字字符后加入%
new_str1 = ''
str2 = 'ds1k3k456//45ka'
for i in str2:
new_str1 += i
if '0' <= i <= '9':
new_str1 += '%'
print(new_str1) # ds1%k3%k4%5%6%//4%5%ka
**4)练习:**将字符串中所有的数字字符都改成 +
str1 = '世界上89Kl22.9;;//sh66-==1'
# '世界上++Kl++.+;;//sh++-==+'
new_str = ''
for i in str1:
if '0' <= i <= '9':
new_str += '+'
else:
new_str += i
print(new_str)
2、字符串乘法运算
1)字符串N、N字符串 - 字符串元素重复N次产生一个新的字符串
str1 = 'abc-'
print(str1)
print(str1 * 3) # abc-abc-abc-
3、字符串比较
1)比较是否相等: ==、!=
print('abc' == 'bca') # False
2)比较大小
- 两个字符串比较大小:比较的是第一对不相等的字符的编码值的大小
- 判断字符的性质:
- 是否是数字字符:‘0’ <= i <= ‘9’
- 是否是小写字母:‘a’ <= i <= ‘z’
- 是否是大写字母:‘A’ <= i <= ‘Z’
- 是否是字母:‘a’ <= i <= ‘z’ or ‘A’ <= i <= ‘Z’
- 是否是中文字符:‘一’ <= i <= ‘\u9fa5’
print('abc' > 'a1c') # True
print('你好' < 'abc') # False
4、in和 not in
- 字符串1 in字符串2: - 字符串1是否是字符串2的子串(字符串2是否包含字符串1)
print('a' in 'abc') # True
print('ab' in 'abc') # True
print('ab' in 'acb') # False
四、字符相关函数
- sum是求数值和,字符串无法进行求和
1、max、min、sorted
print(max('hellow word!')) # w
print(min('hellow,word!')) # !
print(sorted('hellow word!')) # [' ', '!', 'd', 'e', 'h', 'l', 'l', 'o', 'o', 'r', 'w', 'w']
2、len(字符串)
msg = '\tskd,\n'
print(len(msg)) # 6
3、str(字符串)
- 任何数据都可以转换;转换的时候是在数据的打印值外面加引号
str(100)
str(1.26)
list1 = [10, 30, 55]
print(str(list1)) # '[10, 30, 55]'
list1 = ["小明", 19, '男']
print(str(list1)) # ['小明', 19, '男']
4、eval(字符串)
- 去掉字符串的引号获取引号中表达式的结果
eval('100')
print(type(eval('100'))) # <class 'int'>
abc = 100
c = eval('abc') # c=100
d = eval('"abc"')
print(d) # d= 'abc'
b1 = eval('10+20') # b1=10+20=30
print(b1)
msg = 'print(100)'
eval(msg) # 100
- eval的使用案例
a=int(input('输入数值a:'))
b=int(input('输入数值b:'))
value=input('输入一个运算符:(*、-、+、/)')
result=eval(f'a{value}b')
result=eval('a'+value+'b')
print(result)
五、字符串相关方法
1、字符串.join
- 将序列中的元素用指定的字符串连接成一个新的字符串(序列中元素必须全是字符串)
list1 = ['小明', '小花', '王五']
result = 'and'.join(list1)
print(result) # 小明and小花and王五
print('**'.join('123')) # 1**2**3
- 和推导式一起使用
nums = [20, 30, 56]
result = ' + '.join(str(i) for i in nums)
print(result) # 20 + 30 + 56
print(eval(result)) # 106
2、字符串1.count(字符串2)
- 统计字符串1中字符串2的个数
msg = 'how are you ? i am fine, and you?'
result = msg.count('a')
print(result) # 3
print(msg.count('you')) # 2
3、split方法
1)字符串.split(字符串2)
- 将字符串1中前n个字符串2 作为请切割点进行切割 结果是列表
msg = 'how are you ? i am fine, and you?'
result = msg.split('you')
print(result) # ['how are ', ' ? i am fine, and ', '?']
print(msg.split(' ')) # ['how', 'are', 'you', '?', 'i', 'am', 'fine,', 'and', 'you?']
2)字符串.split(字符串2, n)
- 将字符串1中前n个字符串2 作为请切割点进行切割 结果是列表
msg = 'how are you ? i am fine, and you?'
print(msg.split(' ',3)) # ['how', 'are', 'you', '? i am fine, and you?']
4、replace
1)字符串.replace(字符串2,字符串3)
- 将字符串1中所有的字符串2都替换成字符串3
msg = 'how are you ? i am fine, and you?'
result=msg.replace('you','they')
print(result) #how are they ? i am fine, and they?
删除msg中的you
result=msg.replace('you','')
print(result) # how are ? i am fine, and ?
2)字符串.replace(字符串2,字符串3,n) -
- 将字符串1中前n个字符串2都替换成字符串3
result=msg.replace('o','*',2)
print(result) # h*w are y*u ? i am fine, and you?
5、字符串.strip()
- 将字符串两边的空白字符(空格,换行,缩进)给去掉
msg = '''
how are you ? i am fine, and you?
'''
print(msg)
#
#
# how are you ? i am fine, and you?
#
#
print(msg.strip()) # how are you ? i am fine, and you?
去除其他字符(在数据之间的去除不了)
msg='、、、、、、、、、、、、小明、、、、、、、、、、、'
print(msg.strip('、')) # 小明
msg='、、、、、、、、、、、、小、明、、、、、、、、、、、'
print(msg.strip('、')) # print(msg.strip('、')) # 小明
6、字符串.isupper()
- 判断字符串是否是纯大写字母
print('ABCD'.isupper()) # True
7、字符串.islower()
判断字符串是否是纯小写字母
print('abcd'.islower())
9、字符串.upper()
print('abd123ef'.upper()) # ABD123EF
10字符串.lower()
print('ACB123EF'.lower()) # acb123ef
应用:判断字符是否是字母
char='q'
if char.islower() or char.isupper():
print('是字母')
else:
print('不是字母') # 是字母
六、格式化字符串
- 解决的问题:字符串内容不确定的问题
name = '张三'
age = 18
money = 12369.5
1、字符串拼接
msg = name + '今年' + str(age) + '岁'
print(msg) # 小明今年21岁
2、格式字符串
- 语法:包含格式占位符的字符串 % (数据1,数据2,数据3……)
- 注意:()的数据必须和前面字符串中的占位符一一对应
- 常见的格式占位符:
- %s - 可以给任何数据类型占位
- %d - 可以给任何数字占位(整数占位符,如果给的是小数,会自动转换成整数)
- %f - 可以个任何数字占位(浮点数占位符,如果给的是整数,会自动转换成小数,默认保留6位小数)
- %.Nf - 控制保留N位小数
print('x:%s' % [10, 20]) # x:[10, 20]
print('x:%s' % 'acb')
print('x:%s' % 3)
print('x:%s' % 2.69456325)
print('x:%d' % 123) # x:123
print('x:%d' % 12.3) # x:12
result = 'x:%.2f' % 12.564 # x:12.56
print(result)
result = 'x:%f' % 12.564
print(result) # x:12.564000
msg='%s今年%s岁,月薪%s元'%(name,age,money)
print(msg) # 张三今年18岁,月薪12369.5元
3、f-string
- 在字符串最前面(引号的前面)加f,就可以在字符串通过{表达式}中表达式的结果来个字符串提供内容
msg=f'{name}今年{age}岁,月薪{money}元'
print(msg)
a=100
b=30
# xxx*xx=xxx
print(f'{a}+{b}={a+b}') # 100+30=130
-
控制小数位数
{表达式:nf} - 保留n位小数
a=1.23
b=56.34
print(f'{a:.1f}+{b}={a+b}') # 1.2+56.34=57.57
-
{表达式:.n%}
%控制数据显示为百分比,n控制百分比的小数位数
c=0.95
print(f'及格率:{c:.2%}') # 及格率:95.00%
-
{表达式:,.Nf}
标准的金额拼接
# 26598314---->¥26,598,314.00
d=26598314
print(f'¥{d:,.2f}') # ¥26,598,314.00