用 Python 從使用者那裡接受多重輸入
在本教程中,我們將學習如何在Python中從使用者那裡獲取多重輸入。
由使用者輸入的資料將是字串格式。因此,我們可以使用split()方法來分割使用者輸入的資料。
讓我們從使用者那裡獲取多重字串。
示例
# taking the input from the user
strings = input("Enter multiple names space-separated:- ")
# spliting the data
strings = strings.split()
# printing the data
print(strings)輸出
如果您執行以上程式碼,那麼您將得到以下結果。
Enter multiple names space-separated:- Python JavaScript Django React ['Python', 'JavaScript', 'Django', 'React']
如果我們想要獲取多個數字作為輸入該怎麼辦?我們可以使用map和int函式將每個輸入轉換為整數。我們來看一個示例。
示例
# taking the input from the user
numbers = input("Enter multiple numbers space-separated:- ")
# spliting the data and converting each string number to int
numbers = list(map(int, numbers.split()))
# printing the data
print(numbers)輸出
如果您執行以上程式碼,那麼您將得到以下結果。
Enter multiple numbers space-separated:- 1 2 3 4 5 [1, 2, 3, 4, 5]
結論
您可以根據自己的需要修改程式碼並從使用者那裡獲取輸入。如果您在教程中有疑問,請在評論區中提及。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP