How to get both int and string inputs from one input line in python Example: For the given line
10 I love coding
i want to get the 10 and I love coding as separate variables. I tried input[].split[]
but as there is space between I and love there arises a confusion
asked May 23, 2018 at 6:48
Divakar RajeshDivakar Rajesh
1,0122 gold badges17 silver badges22 bronze badges
0
1 Answer
You can limit the split:
>>> input[].split[maxsplit=1]
10 I love coding
['10', 'I love coding']
>>> a,b = input[].split[maxsplit=1]
10 I love coding
>>> a
'10'
>>> b
'I love coding'
answered May 23, 2018 at 6:51
Mark TolonenMark Tolonen
154k23 gold badges162 silver badges233 bronze badges
1
You can use a list comprehension to take n inputs in one line in Python. The input string is split into n parts, then the list comp creates a new list by applying Simple example code Output:int[]
to each of them.n = 2 # how many numbers to accept
numbers = [int[num] for num in input[].split[" ", n-1]]
print[numbers]
The following snippet will map the single line input separated by white space into a list of integers
lst = list[map[int, input[].split[]]]
print[lst]
Output:
1 2 3
[1, 2, 3]
How to take multiple inputs of different data types in one line in Python?
Answer: Example take 2 input values.
x, y = input["Enter a two value: "].split[]
print[x, y]
Output:
Enter a two value: 1 X
1 X
OR
score, name = int[input['Enter Score: ']], input['Enter name:']
print[score]
print[name]
Do comment if you have any doubts and suggestions on this Python input topic.
Note: IDE: PyCharm 2021.3.3 [Community Edition]
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
For instance, in C we can do something like this:
One solution is to use raw_input[] two times.
Another solution is to use split[]
Note that we don’t have to explicitly specify split[‘ ‘] because split[] uses any whitespace characters as a delimiter as default.
One thing to note in the above Python code is, both x and y would be of string. We can convert them to int using another line
x, y = [int[x], int[y]] # We can also use list comprehension x, y = [int[x] for x in [x, y]]
Below is complete one line code to read two integer variables from standard input using split and list comprehension
x, y
=
[
int
[x]
for
x
in
input
[].split[]]
x, y
=
map
[
int
,
input
[].split[]]
This article is contributed by Abhishek Shukla. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above