day10字符串总结和作业
一、字符串相关函数和相关方法
- 相关函数:len、str
str(数据) - 将指定数据转换成字符串(任何类型的数据都可以转换成字符串;转的时候是直接在数据的打印值外面加引号)
print(str(100)) #'100'
print(str(True)) #'True'
list1 = [10,29,30]
print(str(list1)) #'[10, 29, 30]'
list2 = ("abc","田")
print(str(list2)) #"('abc', '田')""
#在交互式环境里面才能显示外面的引号
- eval(字符串) - 计算字符串表达式的结果
str1 = '[10,20,30]'
result = eval(str1)
print(result,type(result)) #[10, 20, 30] <class 'list'>
二、相关方法
- join
字符串.join(序列) - 将序列中的元素用指定字符串拼接成一个字符串(序列中的元素必须是字符串)
list1 = ['name','age','gender']
result = '+'.join(list1)
print(result) #name+age+gender
- split
1)字符串1.split(字符串2) - 将字符串1中所有的字符串2作为切割点对字符串进行切割
str1 = '123*abc*mn'
result = str1.split('*')
print(result) #['123', 'abc', 'mn']
注意1:如果切割点在字符串的开头或者结尾,切完会出现空格
str1 = '*123*abc*mn*'
result = str1.split('*')
print(result) #['', '123', 'abc', 'mn', '']
注意2:如果切割点连续出现,切完后也会出现空串
str1 = '123**abc*mn'
result = str1.split('*')
print(result) # ['123', '', 'abc', 'mn']
2)字符串1.split(字符串2,N) - 将字符串1 中前N个字符串2作为切割点对字符串进行切割
str1 = '123*abc*mn*xyz*你好'
result = str1.split('*', 2)
print(result) #['123', 'abc', 'mn*xyz*你好']
3)字符串1.rsplit(字符串2, N) - 将字符串1倒数前N个字符串2作为切割点对字符串进行切割
str1 = '123*abc*mn*xyz*你好'
result = str1.rsplit('*', 2)
print(result) #['123*abc*mn', 'xyz', '你好']
- replace - 替换
字符串1.replace(字符串2,字符串3) - 将字符串1中所有的字符串2都替换成字符串3
str1 = 'how are you? i am fine, thank you! and you?'
result = str1.replace('you', 'me')
print(result) # 'how are me? i am fine, thank me! and me?'
字符串1.replace(字符串2,字符串3, N) - 将字符串1中前N个字符串2的替换成字符串3
str1 = 'how are you? i am fine, thank you! and you?'
result = str1.replace('you', 'me', 2)
print(result) # how are me? i am fine, thank me! and you?
- 替换字符
str.maketrans(字符串1,字符串2) - 创建字符串1中所有字符和字符串2中所有字符一一对映关系表
字符串.translate(字符对映表) - 按照字符対映表的关系将字符串中的字符进行替换
str1 = 'abnsmahsjdbmnsdxybksdall'
table = str.maketrans('ab', '12')
result = str1.translate(table)
print(result) # '12nsm1hsjd2mnsdxy2ksd1ll'
- 删除字符串两端的空白
-
字符串.strip() - 删除字符串两边的空白
-
字符串.rstrip() - 删除字符串右边的空白
-
字符串.lstrip() - 删除字符串左边的空白
str1 = '\t \n a b c \n\n'
print(str1.strip()) #a b c
print(str1.lstrip()) #a b c
print(str1.rstrip()) #a b c
- count - 统计个数
字符串1.count(字符串2) - 统计字符串1中字符串2出现的次数
str1 = 'how are you? i am fine, thank you! and you?'
print(str1.count('o')) #4
print(str1.count('you')) #3
三、格式字符串
- 字符串格式化
字符串拼接
name = '小明'
age = 18
message = name + '今年' + str(age) + '岁!'
print(message)
- 格式字符串
1)格式字符串:包含格式占位符的字符串 % (数据1,数据2,数据3,…)
注意:()中的数据必须和字符串占位符一一对应
2)格式占位符
%s - 字符串占位符,可以对应任何类型的数据
%d - 整数占位符,可以对应任何数字
%f - 浮点数占位符,可以对应任何数字
%f.Nf - 浮点数占位符,可以对应任何数字,让数字保留N位小数
name = '小明'
age = 18
money = 18000.8
gender = '男'
message = '%s, 性别:%s, 年龄:%d, 月薪: %.2f元!' % (name, gender, age, money)
print(message)
- f-string
1)基本用法
语法:f’{表达式}’ - 将{}中表达式的值作为字符串内容拼接到字符串中
name = '小明'
age = 18
money = 18000.8
gender = '男'
message = f'{name}, 性别:{gender}, 年龄:{age}, 月薪:{money}元!'
print(message)
2)加参数
f’{提供数据表达式:参数}’
a. 控制小数位数的参数
f’{表达式:.Nf}’ - 保留N位小数
money = 223.8
result = f'金额:{money:.2f}元'
print(result) #金额:223.80元
b. 金额数值显示加逗号
只加逗号:f’{表达式:,}’
money = 1800000
result = f'¥{money:,.2f}'
print(result) #¥1,800,000.00
c. 显示百分号
f’{表达式:.N%} - N控制百分数的小数位数
x = 0.34
result = f'增长率:{x:.1%}'
print(result) #增长率:34.0%
d. 控制长度
f’{表达式:字符>N}’ 、 f’{表达式:字符<N}’
num = 8
result = f'py2101{num:0>3}'
print(result) #py2101008
作业
-
编写一个程序,交换指定字典的key和value。
例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}
dict1={'a':1, 'b':2, 'c':3} dict2={} for key, value in dict1.items(): key, value = value , key dict2.setdefault(key, value) print(dict2)
-
编写一个程序,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
例如: 传入'12a&bc12d-+' --> 'abcd'
str1 = '12a&bc12d-+' str2 = '' for x in str1: if 'a' <= x <= 'z' or 'A' <= x <= 'Z': str2 += x print(str2)
-
写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
例如: 'abc' -> 'Abc' '12asd' --> '12asd'
str1 = input('请输入一个字符串:') if not('a' <= str1[0] <= 'z'): print(str1) else: num = chr(ord(str1[0]) - 32) print(num + str1[1:])
-
写程序实现endswith的功能,判断一个字符串是否已指定的字符串结束
例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True 字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
str1 = 'abc231ab' str2 = 'ab' if str1[-len(str2)::] == str2: print(True) else: print(False)
-
写程序实现isdigit的功能,判断一个字符串是否是纯数字字符串
例如: '1234921' 结果: True '23函数' 结果: False 'a2390' 结果: False
str1 = input('请输入一个字符串:') for x in str1: if not '0' <= x <= '9': print('不是纯数字') break else: print('是纯数字')
-
写程序实现upper的功能,将一个字符串中所有的小写字母变成大写字母
例如: 'abH23好rp1' 结果: 'ABH23好RP1'
str1 = 'abH23好rp1' str2 = '' for x in str1: if 'a' <= x <= 'z': x = chr(ord(x) - 32) str2 += x print(str2)
-
写程序获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
例如: 序列:[-7, -12, -1, -9] 结果: -1 序列:'abcdpzasdz' 结果: 'z' 序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98} 结果: 98
str1 = input('请输入一个序列:') new_list = [] if type(eval(str1)) == dict: dict1 = eval(str1) for i in dict1: new_list.append(dict1[i]) print(max(new_list)) elif type(eval(str1)) == list: print(max(list1)) else: print(max(eval(str1)))
-
写程序实现replace函数的功能,将指定字符串中指定的旧字符串转换成指定的新字符串
例如: 原字符串: 'how are you? and you?' 旧字符串: 'you' 新字符串:'me' 结果: 'how are me? and me?'
str1 = 'how are you? and you?' str2 = 'you' str3 = 'me' result=str3.join(str1.split(str2)) print(result)
-
写程序实现split的功能,将字符串中指定子串作为切割点对字符串进行切割
例如:原字符串: 'how are you? and you?' 切割点: 'you' 结果: ['how are ', '? and ', '?']
str1 = 'how are you? and you?' str2 = 'you' new_str = '' i = 0 while i < len(str1): if str2 == str1[i: i + len(str2)]: i += len(str2) new_str += ',' else: new_str += str1[i] i += 1 print(new_str)
-
用思维导图总结四大容器:列表、字典、元组、集合