插入字母和数字 - 将字母向右偏移'数字'次

0 投票
4 回答
733 浏览
提问于 2025-04-17 21:15
def char():
    letter = str(input("Input Letter from alphabet: "))
    x = int(input("Input Value to shift letter to the right x number of times: : "))
    newLetter = ord(letter) + x
    if newLetter > 90 and newLetter < 97:
        remainder = newLetter % 90
        newLetterI = 65 + remainder
        print(chr(newLetterI))
    elif newLetter > 122:
        remainder = newLetter % 122
        newLetterI = 97 + remainder
        print(chr(newLetterI))

char()

这是我的代码,它可以把字母向右移动一定的次数。虽然这个代码写得有点啰嗦,但这是我找到的唯一一种方法,这样做不会出现我不太理解的错误。我只是想知道这样做是否可以,以及当字母移动到Z或z后再回到开头是否也可以。

4 个回答

0

在我看来,这种方式是最容易理解的:

import string

def shiftchar(char, n):
    if char.isupper(): 
        letters = string.uppercase # all uppercase letters in alphabetical order
    elif char.islower():
        letters = string.lowercase # all lowercase letters in alphabetical order
    try:
        initcharpos = letters.index(char)
        newchar = letters[(initcharpos + n) % 26]
        # get the letter n characters later, with wraparound
        return newchar
    except (NameError, ValueError):
        # NameError: char is mixed-case or non-English, so letters is never defined
        # ValueError: char not found in letters; probably a multi-char string
        raise TypeError("Expected a single English char as first argument")

print shiftchar('A', 5)   # F
print shiftchar('z', 1)   # a
print shiftchar('foo', 5) # TypeError
0

我发现你代码中的一个问题是,循环的处理方式似乎不太合理。如果你对新的字母进行122取模,当你进行26的位移时,就会遇到问题。而且,这样写也有点难懂,因为你需要记住ASCII值。

我来试着解释一个稍微改进的版本:

letter = input("Enter a letter from the alphabet: ") # No need for str, it is already a string
shift = int(input("Enter your letter shift: "))

if letter.islower(): # Much better than worrying about ascii values
    initial = 'a'
else:
    initial = 'A'

letterIndex = (ord(letter) - ord(initial)) # So 'a' would have index 0, 'b' 1, 'z' 25
newIndex = (letterIndex + shift) % 26 # Making sure our index is from 0 to 25
newLetter = chr(ord(initial) + newIndex) # after 'a' or 'A', increment by newIndex
print newLetter

这里有一个更简洁的版本,没有注释:

letter = input("Enter a letter from the alphabet: ")
shift = int(input("Enter your letter shift: "))

initial = 'a' if letter.islower() else 'A'

newIndex = (ord(letter) - ord(initial) + shift) % 26
print(chr(ord(initial) + newIndex))
0

你应该像这样使用

import sys
def char():
    letter = sys.stdin.readline().strip()
    x = int(sys.stdin.readline())
    oldLetter = ord(letter)
    if oldLetter > 64 and oldLetter < 91:
        if (oldLetter+x) <= 90:
            remainder = (oldLetter + x) % 65
            newLetter = 65 + remainder
        else:
            remainder = (oldLetter + x) % 90
            newLetter = 64 + remainder
        print(chr(newLetter))
    elif oldLetter > 96 and oldLetter < 123:
        if (oldLetter+x) <= 122:
            remainder = (oldLetter + x) % 97
            newLetter = 97 + remainder
        else:
            remainder = (oldLetter + x) % 122
            newLetter = 96 + remainder
        print(chr(newLetter))
char()
0

请你检查一下这个:

#!/usr/bin/python

def next_nchar(char, n):
    # 97, 122
    upper = None
    if char.isupper():
        upper = True
    lw = char.lower()
    start = ord(lw)
    num = ord(lw) + n
    if num > 122:
        ex = num - 122
    else:
        ex = None
    if not ex:
        r = range(start, num)
    else:
        r = range(start, 123) + range(97, 97+ex-1)
    if upper:
        return [chr(x).upper() for x in r]
    return [chr(x) for x in r]

for i in ['a', 'k', 'y', 'P']:
    print next_nchar(i, 5)

输出结果:

['a', 'b', 'c', 'd', 'e']
['k', 'l', 'm', 'n', 'o']
['y', 'z', 'a', 'b', 'c']
['P', 'Q', 'R', 'S', 'T']

撰写回答