<p>我找到了一种不用maketrans()的方法。我不想依赖这样的功能,所以我自己做了。我花了几个小时才弄明白:</p>
<pre><code>def shiftAll(text, shift):
'''
@param text - string of text to be shifted
@param shift - the number of times to shift all letters; int value only
In range 'a' to 'z' and 'A' to 'Z'
Initializes empty string newText and appends the new shifted letters to it
To shift right on th alphabet ex: a -> b or n -> y,
enter a positive shift ex: 1, 2, 4
To shift left on the alphabet ex: b -> a or q -> m,
enter a negative shift ex: -2, -1, -5
Handles:
Error where index out of range
Sum of shift and position is greater than 25 or less than 0
~Allows cases where the letter may be 'a'(j (position) == 0)
but the shift is negative
~Allows cases where the letter may be 'z'(j (position) == 25)
but the shift is positive
returns newText
'''
alpha = "abcdefghijklmnopqrstuvwxyz"
newText = ""
for i in text:
if ((i not in alpha) and (i not in alpha.upper())):
newText += i #only replaces alphabetical characters
for j in range(len(alpha)): #26 letters, so positions 0-25
if ((i == alpha[j]) or (i == alpha[j].upper())):
while (j + shift > 25): #to avoid index out of range error
shift -= 26
while (j + shift < 0): #to avoid index out of range error
shift += 26
if(i == alpha[j].upper()): #because letters can be capital too
newText += alpha[j + shift].upper()
else:
newText += alpha[j + shift]
return newText
string = input("Enter anything with letters in it: ")
aShift = int(input("Enter how many places you want to shift the letters: ")
#let's pretend the user will actually enter an int value in aShift
result = shiftAll(string, aShift)
print(result)
</code></pre>
<p>这对任何字符串都有效,并按班次移动字符串中的所有字母。班次必须是整数</p>