Python – 按 K 反转 Shift字符
给定一个字符串,将每个字符根据其字母位置反向移位 K,包括循环移位。
Input : test_str = ‘bccd’, K = 1
Output : abbc
Explanation : 1 alphabet before b is ‘a’ and so on.
Input : test_str = ‘bccd’, K = 2
Output : zaab
Explanation : 2 alphabets before b is ‘z’ (rounded) and so on.
方法:使用 maketrans() + upper() + list comprehension + translate() + slicing
在此,我们使用 maketrans() 和切片将每个字符的转换表转换为 K 移位版本。 upper() 用于处理所有大写字符, translate() 用于根据 maketrans() 创建的查找翻译表进行翻译。
Python3
# Python3 code to demonstrate working of
# Reverse Shift characters by K
# using maketrans() + upper() + list comprehension + translate() + slicing
# initializing string
test_str = 'GeeksForGeeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 10
alpha_chars = 'abcdefghijklmnopqrstuvwxyz'
# converted to uppercase
alpha_chars2 = alpha_chars.upper()
# maketrans used for lowercase translation
lower_trans = str.maketrans(alpha_chars, alpha_chars[ -K:] + alpha_chars[ : -K])
# maketrans used for uppercase translation
upper_trans = str.maketrans(alpha_chars2, alpha_chars2[ -K:] + alpha_chars2[ : -K])
# merge lookups
lower_trans.update(upper_trans)
# make translation from lookups
res = test_str.translate(lower_trans)
# printing result
print("The converted String : " + str(res))
输出
The original string is : GeeksForGeeks
The converted String : WuuaiVehWuuai