简体   繁体   中英

How to print the letter of a certain string that the user wants

I'm new to python and have a question. I want to create a program that ask the user for a number between 1 and 26. Then use this response to print the corresponding letter of the alphabet (a is the 1st letter, b is the 2nd letter, z is the 26th letter, etc). If there is an IndexError, print ("Your number is out of range"). For all other errors, print("Something else occurred").

Right now I have this:

try:
    theAlphabet = "abcdefghijklmnopqrstuvwxyz"
    alphabet=input("Give me a number between 1 and 26.")
    print(len(theAlphabet)

except IndexError:
    print("Your number is out of range")
except: 
    print("Something else occurred")

I dont know what to do after the print(len(theAlphabet) part.

print(chr(ord("a")+alphabet))

ord("a") gives you the ASCII value of the letter "a". Then you can add the number. chr(x) gives you the ASCII character for a value. Note that this is not checking for errors on the range, but it's probably best to do that another way.

You can access the string with an index, but you will need to convert the user input to an interger using int() and also reduce the value by 1.

try:
    theAlphabet = "abcdefghijklmnopqrstuvwxyz"
    alphabet=input("Give me a number between 1 and 26: ")
    print(len(theAlphabet))
    print(theAlphabet[int(alphabet)-1])

except IndexError:
    print("Your number is out of range")
except: 
    print("Something else occurred")

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