簡體   English   中英

如何打印用戶想要的某個字符串的字母

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

我是 python 的新手,有一個問題。 我想創建一個程序,要求用戶輸入 1 到 26 之間的數字。然后使用此響應打印字母表中的相應字母(a 是第一個字母,b 是第二個字母,z 是第 26 個字母,等等)。 如果出現 IndexError,請打印 ("Your number is out of range")。 對於所有其他錯誤,打印(“發生其他事情”)。

現在我有這個:

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

我不知道在print(len(theAlphabet)部分之后該做什么。

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

ord("a") 為您提供字母“a”的 ASCII 值。 然后你可以添加號碼。 chr(x) 為您提供值的 ASCII 字符。 請注意,這不是檢查范圍內的錯誤,但最好以另一種方式進行。

您可以使用索引訪問字符串,但您需要使用int()將用戶輸入轉換為整數,並將值減少 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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM