Skip to content

Input split Python | Example code

  • by

If you want to split input by space or any other splitter then just use the split method with the input function in Python.

split slits a string by a space by default, but you can change this behavior:

input().split(separator, maxsplit)

Example Input split Python

Simple example code split input by space.

res = input("Write:").split(" ")

print(res)

Output:

Input split Python

OR

input("Please enter two digits separated by space").split()

Note: that .split(" ") isn’t needed as that is what it is by default.

Take 2 integer values

x, y = map(int, input().split())  # you can change the int to specify or intialize any other data structures

print(x)
print(y)

Output:

1 2
1
2

How to get user input of list in Python?

# number of elements 
n = int(input("Enter number of elements : "))

# Below line read inputs from user using map() function  
a = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]

print("\nList is - ", a)

Output:

Enter number of elements: 2

Enter the numbers: 1 2

List is – [1, 2]

Do comment if you have any doubts or suggestions on this Python input program code.

Note: IDE: PyCharm 2021.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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.