一个代码实现:
一些基础知识不过关,如下:
1. 判断大小写字母:isuppper()
和islower()
2. 大小写互换:uppper()
和lower()
3. 字母转为数字:ord()
4. 数字转回字母:chr()
5. 列表转为字符串:''.join(l)
,其中l
为一个列表
6. 字符串转为列表:list(s)
,其中s
为一个字符串
7. 字符串中替换:s.replace(old,new)
下列代码实现的功能为:(i) 将大小写字母互换; (ii) 将字母加1,得到下一个字母。
def One(ll: str):
temp = list(ll)
length = len(temp)
for i in range(length):
if temp[i].islower():
temp[i] = temp[i].upper()
elif temp[i].isupper():
temp[i] = temp[i].lower()
# list 转为 str
return ''.join(temp)
def Two(ll: str):
temp = list(ll)
length = len(temp)
for i in range(length):
if temp[i] == 'z':
temp[i] = 'a'
elif temp[i] == 'Z':
temp[i] = 'A'
else:
temp[i] = chr(ord(temp[i]) + 1)
#ord(): ASCII chr(): 转回字符
# list 转为 str
return ''.join(temp)
n, q = map(int, input().split())
s = input()
for i in range(q):
opt, l, r = map(int, input().split())
if opt == 1:
s = s.replace(s[(l - 1):r], One(s[(l - 1):r]))
print(s)
if opt == 2:
s = s.replace(s[(l - 1):r], Two(s[(l - 1):r]))
print(s)
由于python中字符串是不可直接修改的,上文中处理字符替换使用了先转换为列表再换回字符串,这样也可以较好的处理有重复字符的情况