How to Return Comma Separated Values in Python?

Estimated read time 1 min read

To return comma-separated values in Python, you can convert a list of values to a string using the join() method and specify the comma as the separator. Here’s an example:

def get_csv_values(input_list):
    csv_values = ','.join(str(value) for value in input_list)
    return csv_values

my_list = [1, 2, 3, 4, 5]
result = get_csv_values(my_list)
print(result)  # Output: "1,2,3,4,5"

In the code above, the get_csv_values() function takes an input list and uses a generator expression (str(value) for value in input_list) to convert each value in the list to a string. The join() method then concatenates these values into a single string, using a comma , as the separator.

The resulting string csv_values will contain the values from the list separated by commas. In this example, the output will be "1,2,3,4,5".

You can adjust the separator character as needed. For example, if you want to use a different separator such as a semicolon ;, you can modify the ','.join() statement to ';'.join().

By using the join() method, you can easily create a comma-separated string from a list of values or any iterable in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply