1.字符串的搜索
定义字符串s = 'hello westos hello'
find找到子串,并返回最小的索引,rfind找到子符串,并返回最大的索引
print(s.find(‘hello’))
print(s.find(‘westos’))
print(s.rfind('hello'))
2.字符串的替换
.replace更换字符
s = 'hello westos hello'
print(s.replace('hello','word')) 把hello换成Word
3.字符串的对齐
.center(参数)
print('系统管理'.center(30)) 两边各30各空格
print('系统管理'.center(30,'*')) 两边各30各*
print('系统管理'.center(30,'!'))
print('系统管理'.ljust(30,'@')) 右边30各@
print('系统管理'.rjust(30,'#')) 左边30各#
4.字符串的统计
.count('元素') 统计
s = 'hello westos hello'
print('hello'.count('h'))
print(s.count('l'))
5.字符串的分离
s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])
6.字符串的连接
.join(变量称)连接 .split(变量名称)分开
date = '2020-04-19'
date1 = date.split('-')
print(date1)
print(''.join(date1))
print('*'.join(date1))
字符串特性的应用
习题1
.给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个字符:
‘A’ : Absent,缺勤
‘L’ : Late,迟到
‘P’ : Present,到场
如果一个学生的出勤纪录中不超过一个’A’(缺勤)并且不超过两个连续的’L’(迟到),那么这个学生会被奖赏。
你需要根据这个学生的出勤纪录判断他是否会被奖赏。
示例 1:
输入: “PPALLP”
输出: True
示例 2:
输入: “PPALLL”
输出: False
s = input('出勤记录: ') 输入出勤记录
if s.count('A') <= 1 and s.count('LLL') == 0: 判断出勤记录
print('ture')
else:
print('false')
打印结果:
出勤记录: ALLLPP
false
出勤记录: PPALP
ture
方法2:
print(s.count('A') <= 1 and s.count('LLL') == 0 )
打印结果
出勤记录: APPLL
True
习题2
给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用
空格分割, 单词之间只有一个空格,前后没有空格。
比如: (1) “hello xiao mi”-> “mi xiao hello”
输入描述: 输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)
输出描述:对于每个测试示例,要求输出句子中单词反转后形成的句子
示例1:
输入
hello xiao mi
输出
mi xiao hello
li = input('输入语句:').split(' ')
print(' '.join(li[::-1]))
打印结果
输入语句:hello xiao mi
mi xiao hello
方法二:
print(' '.join(input('输入语句: ').split()[::-1]))
打印结果
输入语句: hello xiao mi
mi xiao hello