简体   繁体   中英

insert letter and number - shift letter to right in alphabet 'number' of times

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()

This is my code that shifts the letter to the right a 'number' of times. It is very long winded, but it was the only way i found how to do it without having lots of errors that i didn't really understand. I was just wondering if it is ok, and was just wondering if the wrapping back around once the alphabet reached Z or z ok.

Could you please check this:

#!/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)

Output:

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

you should use like this one

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()

One problem I can find with your code is that the wraparound doesn't seem to make much sense. If you modulo 122 your newLetter, you will run into problems when you have shifts of 26, for example, and also it's a bit hard to read since you have to remember ascii values.

I will try to explain a slightly improved version:

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

Here is a more concise version of it, without comments:

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))

This is the most readable way to do it, IMO:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM