How to Take Comma-Separated Input in Python

In Python, there are many circumstances when you may need to take comma-separated input in your script or program. For new coders, this can seem like a daunting task.

However, Python provides a few straightforward methods to accomplish this using the split function and the CSV library.

In this tutorial, you will learn how to take comma-separated input using both methods.

Method 1: Using the split Function

Python’s built-in string function, split, can be used to separate a comma-separated input. Here’s how to do it:

  1. First, take input from the user using Python’s input function.
  2. Next, use the split function to separate the user’s input at each comma.
  3. The split method will return a list of items. You can print this list or use it in your program as needed.

Here’s an example:

Enter comma-separated values:
45,6
List of Items: ['45', '6']

Method 2: Using the CSV Library

Python’s CSV library offers built-in methods to read and write CSV (Comma Separated Values) files. It provides the function reader which is used to read the CSV file and returns a reader object which iterates throughout lines in the CSV file and is used to fetch the data in the CSV file.

Here’s how to do it:

  1. First, import the CSV library using import csv.
  2. Create a CSV file reader using the csv.reader function.
  3. Then, process each row of the CSV file individually in a loop context to get every record separately.

Here’s an example:

Conclusion

Python provides a number of methods for handling comma-separated input. The split function offers a quick and easy way to separate a string based on a delimiter.

The CSV library allows you to read and write CSV files and offers flexibility when it comes to working with files containing comma-separated data. Which method you choose depends on your specific needs. Happy coding!