编写函数:给定义个小写英文字符串str和一个非负整数k(0<=k<26),将str中的每个小写字符替换成编码表码值中比它大k的字母。规定字母z和字母a相连,如果超过了字母z就回到了字母a。对
函数运行使用关键字参数的方式传递参数。
基于Monster 组和GPT的调写:
def encode_string(str, k):
result = ""
for char in str:
if char.isalpha() and char.islower():
# 计算新字符的 ASCII 码值
new_ascii = ord(char) + k
if new_ascii > ord('z'):
# 如果超过字母 z,则回到字母 a
new_ascii = ord('a') + new_ascii - ord('z') - 1
# 将新字符添加到结果字符串中
result += chr(new_ascii)
else:
# 对于非小写字母字符,直接添加到结果字符串中
result += char
return result
# 示例
encoded_str = encode_string(str="hello, world!", k=3)
print(encoded_str) # "khoor, zruog!"
def replace_str(str="", k=0):
new_str = ""
for char in str:
new_ord = ord(char) + k
if new_ord > ord('z'):
new_ord = new_ord - 26
new_char = chr(new_ord)
new_str += new_char
return new_str
result = replace_str(str="abcxyz", k=5)
print(result) # 输出 "fghcde"
代码如下,有用请采纳
def str_convert(s, k):
con_chr = 'abcdefghijklmnopqrstuvwxyz' * 2
result = ''
for alpha in s:
index = con_chr.index(alpha)
result += con_chr[index + k]
return result
s = 'amz'
k = 25
print(str_convert(s, k))