Open In App

Input a comma separated string – Python

Last Updated : 12 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an input string that is comma-separated instead of space. The task is to store this input string in a list or variables. This can be achieved in Python using two ways:

  • Using List comprehension and split()
  • Using map() and split()

Using List comprehension and split()

Using list comprehension with split() allows for quick and flexible conversion of input into a list of integers or other types. split() function helps in getting multiple inputs from the user. It breaks the given input by the specified separator. If the separator is not provided then any white space is used as a separator.  

Python
# Taking 2 inputs
a, b = [int(x) for x in input("Enter two values\n").split(', ')]
print("\nThe value of a is {} and b is {}".format(a, b))

# Taking 3 inputs
a, b, c = [int(x) for x in input("Enter three values\n").split(', ')]
print("\nThe value of a is {}, b is {} and c is {}".format(a, b, c))

# Taking multiple inputs
L = [int(x) for x in input("Enter multiple values\n").split(', ')]
print("\nThe values of input are", L)

Output:

Enter two values
1, 2

The value of a is 1 and b is 2
Enter three values
1, 2, 3

The value of a is 1, b is 2 and c is 3
Enter multiple values
1, 22, 34, 6, 88, 2

The values of input are [1, 22, 34, 6, 88, 2]

Explanation:

  • split(‘, ‘) method splits the input string by commas and spaces into a list of substrings.
  • list comprehension [int(x) for x in input().split(‘, ‘)] iterates through the substrings and converts each one to an integer.

Using map() and split()

map() function is a concise and efficient way to convert a comma-separated string input into a list of integers. map() function returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.) 

Python
# Taking 2 inputs
a, b = map(int, input("Enter two values\n").split(', '))
print("\nThe value of a is {} and b is {}".format(a, b))

# Taking 3 inputs
a, b, c = map(int, input("Enter three values\n").split(', '))
print("\nThe value of a is {}, b is {} and c is {}".format(a, b, c))

# Taking multiple inputs
L = list(map(int, input("Enter multiple values\n").split(', ')))
print("\nThe values of input are", L)

Output:

Enter two values
1, 2

The value of a is 1 and b is 2
Enter three values
1, 2, 3

The value of a is 1, b is 2 and c is 3
Enter multiple values
1, 2, 3, 4

The values of input are [1, 2, 3, 4]

Explanation:

  • split(‘, ‘) method splits the input string into a list of substrings based on commas and spaces.
  • map(int, input().split(‘, ‘)) applies the int() function to each element of the list.


Next Article
Practice Tags :

Similar Reads