我正在嘗試獲取輸出以用文字顯示您輸入的數字:
phone = input("Phone: ")
digits_mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine"
}
output = ""
for character in phone:
output = digits_mapping.get(character) ", "
print(output, end="")
例如,如果輸入等于545,我會得到Five, Four, Five,
如何得到Five, Four, Five!
uj5u.com熱心網友回復:
回圈中的字串連接在 Python 中通常是一個壞主意(多次執行時還不錯)。相反,您可以使用串列并將專案附加到它。然后使用.join(). 對于列印,您需要指定end=引數 to'!\n'而不是 default '\n'。
output = [digits_mapping[char] for char in phone]
print(", ".join(output), end='!\n')
您還可以使用生成器運算式:
print(", ".join(digits_mapping[char] for char in phone), end='!\n')
另一種方法是構建字串,'!'然后使用普通列印:
print(", ".join(digits_mapping[char] for char in phone) '!')
uj5u.com熱心網友回復:
這是另一種策略 - 檢查您是否在串列中的最后一項。如果是,請附加“!” - 否則,附加“,”。
phone = input("Phone: ")
digits_mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine"
}
output = ""
for i in range(len(phone)):
if i == len(phone) - 1:
output = digits_mapping.get(phone[i]) "!"
else:
output = digits_mapping.get(phone[i]) ", "
print(output, end="")
uj5u.com熱心網友回復:
任何時候創建字符分隔串列時,最好將串列的成員寫入串列物件并使用join()輸出分隔字串。在任何語言中都是如此(盡管您使用的通常是陣列,而不是串列)。反而:
phone = input("Phone: ")
digits_mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine"
}
words = []
for character in phone:
words.append(digits_mapping.get(character))
print(",".join(words) "!", end="")
uj5u.com熱心網友回復:
最后只列印字串的副本,除了最后 2 個字符(空格和逗號:“,”),并在您的結束引數中添加您想要的感嘆號。你的最后一行看起來像這樣:
print(output[:-2], end="!")
uj5u.com熱心網友回復:
我建議在 之后for,您重新分配output給自己,省略最后一個字符(“,”)。然后你output用“!”連接。
output=output[0:len(output)-1]
output ="!"
我希望我對你有所幫助。有一個很好的編碼會議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/433032.html
上一篇:負for回圈中的變數賦值
