[英]Python recognize two digit numbers as seperate numbers in my if statement?
[英]Listing two digit numbers in python
我正在嘗試使用我的程序平均3年級,我的所有數學知識都下降了,但是我不確定如何使用一個input
命令來獲得3個單獨的變量。 例如,用戶應該在一個輸入語句中輸入3個等級,但是如何將它們分開? 我的方法: grade = list(input("Three test scores: "))
輸出grade = ['2', '3', ',', ' ', '1', '2', ',', ' ', '5', '4']
給定grade1 = 23
23, 12, 54
我的期望輸出是grade1 = 23
grade3 = 54
grade2 = 12
grade3 = 54
有幫助嗎?
嘗試:
grades = input('Three test scores: ')
grade1, grade2, grade3 = grades.split(', ')
將所有非數字字符(不僅僅是逗號)作為分隔符的通用解決方案:
import re
grade1, grade2, grade3 = re.findall(r'\d+', grades)
嘗試使用.split(", ")
分割輸入。 這應該返回您一個字符串列表。
然后使用map
將它們轉換為int。 map
接受一個函數(在本例中為int
)並將該函數應用於一系列值。
>>> inputs = input("Three test scores: ").split(", ")
Three test scores: 1, 2, 3
>>> grade1, grade2, grade3 = map(int, inputs)
>>> grade1
1
>>> grade2
2
>>> grade3
3
或更緊湊:
grade1, grade2, grade3 = map(int, input("Three test scores: ").split(", "))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.