-4

I am trying to do some coursework but I have hit a wall. I am trying to write a function that takes a letter and a digit as the inputs, and returns the letter shifted key positions to the right in the alphabet. This is what I have so far:

def code_char(c,key):
    letter=input("Enter letter to be moved")
    shift=int(input("Enter degree of shift"))
    letter=ord(letter)    

    if letter>=65 and letter <=90: 
          letter=letter+shift
          while letter>90:
                  letter=letter-26

    elif letter>=97 and letter <=122:
          letter=letter+shift
          while letter>122:
                  letter=letter-26

    letter=chr(letter)
    print(letter)

code_char("",0)

The problem is the letter=ord(letter) as I keep getting TypeError: ord() expected string of length 1, but list found. I have tried different variations. I need to convert the input 'letter' into ASCII.

4

1 回答 1

-4

正如 Willem 在 OP 评论中所建议的那样,input()给你一个str包含字母和换行符的 char\n.strip()如果你使用的是旧的 Python 版本,请使用它来解决它:

def code_char():
    letter = ord(input("Enter letter to be moved").strip())
    shift = int(input("Enter degree of shift"))

    if (letter >= 65) and (letter <= 90):
        letter += shift
        while (letter > 90):
            letter -= 26
    elif (letter >= 97) and (letter <= 122):
        letter += shift
        while letter > 122:
            letter -= 26

    print(chr(letter))

code_char()

新的 Python 版本(例如 3.6.0)不应该需要这.strip()部分,因为在格式化编辑后我的代码工作得很好:

def code_char():
    letter = ord(input("Enter letter to be moved"))
    shift = int(input("Enter degree of shift"))

    if (letter >= 65) and (letter <= 90):
        letter += shift
        while (letter > 90):
            letter -= 26
    elif (letter >= 97) and (letter <= 122):
        letter += shift
        while letter > 122:
            letter -= 26

    print(chr(letter))

code_char()
于 2017-03-13T14:27:33.390 回答