字符串特性
- 索引:字符串的索引默认从0开始,到len(str)-1结束。例如str[0]
- 切片:
- 切片的规则: str[start:end:step] 从start开始,到end-1结束,步长:step
print(str[0:3])
print(str[0:4:2])
- 显示所有字符
print(s[:])
- 显示前3个字符
print(s[:3])
- 字符串逆序输出
print(s[::-1])
- 除了第一个字符以外,其他全部输出
print(s[1:])
- 重复
print( s * 10)
- 连接
print('hello' + ' ' + 'world'
- 成员操作符
print('h' in s)
print('q' in s)
示例:判断是否为回文串
while True:
print('输入一个字符串:')
str = input()
if str == str[::-1]:
print('%s是回文串' %str)
else:
print("%s不是回文串" %str)
结果:
字符串常用方法
这里就要使用的字符串内置的一些方法了
常用方法 | 含义 |
---|---|
str.isdigit() | 是否为数字 |
str.isalpha() | 是否为字母 |
str.isalnum() | 是否为字母和数字的组合 |
str.istitle() | 是否只有首字母大写 |
str.isupper() | 是否是大写字母 |
str.islower() | 是否是小写字母 |
str.upper() | 转换成大写 |
str.lower() | 转换成小写 |
isinstance(‘a’,str) | 来判断一个对象是否是一个已知的类型 |
str.strip() | 去掉字符串两边的空格或者\n或者\t |
str.strip(‘h’) | 去掉字符串两边的字符‘h’ |
str.lstrip() | 去掉左边的空格 |
str.rstrip() | 去掉右边的空格 |
str.startswith() | 字符串匹配开头 |
str.endwith() | 字符串匹配结尾 |
str.find(‘hello’) | find找到子串,并返回最小的索引 |
str.rfind(‘hello’) | rfind找到子串,并返回最大的索引值 |
str.replace(‘hello’,‘westos’) | 替换字符串中所有的‘hello’为‘westos’ |
str.count(‘ll’) | 字符串统计子串ll的个数 |
str.center(10,’*’) | 字符串居中对齐 |
str.ljust(10,’*’) | 字符串居左对齐,以*为分隔 |
str.rjust(10,’*’) | 字符串居右对齐,以*为分隔 |
str.split(’.’) | 字符串分离,默认是以空格 |
‘/’.join(date1) | 字符串分离后的连接,以指定的字符连接 |
实例1:判断变量名是否合法
while True:
print("请输入变量名:")
str = input()
#先判断首字符
if str[0] == '_' or str[0].isalpha():
if str.isalnum() or '_' in str:
print("变量名合法")
else:
print('变量名不合法')
else:
print('首字符不合法!')
测试结果:
实例2:倒序输出一句话(单词逆序)(很经典!!)
实例:
输入
hello xiao mi
输出
mi xiao hello
while True:
print("请输入一段英文句子:")
print(' '.join(input().split()[::-1]))
实例3:去除字符串元音字符
输入
They are students.
aeiou
输出
Thy r stdnts.
while True:
print("请输入一段英文句子:")
str = input()
print('你想剔除的字符:')
target = input()
for i in str:
if i in target:
str = str.replace(i,'')
print(str)
结果:
实例4:考勤记录奖励
给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以
下三个字符:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两>个连续的'L'(迟到),
那么这个学生会被奖赏。
你需要根据这个学生的出勤纪录判断他是否会被奖赏。
示例 1:
输入: "PPALLP"
输出: True
示例 2:
输入: "PPALLL"
输出: False
while True:
print('请输入考勤记录:')
report = input()
print(report.count('A') <= 1 and report.count('LLL') == 0)
结果: