
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Python CSV String to Array
The comma-separated values (CSV) is a text format that is used for storing tabular data. In Python, we will come across situations where CSV data is available in string format. For performing operations on this data, we need to convert it into an array. Python provides multiple ways to achieve this conversion.
In this article, we are going to learn about converting the CSV string into an array.
Using Python split() Method
In this approach, we are going to use the Python split() method, which is used to split all the words in a string separated by a specified separator. Here, this method accepts a separator (character at which the string should be split) and a delimiter as parameters.
Since the input is a CSV (i.e., the values will be comma-separated), we will be setting the delimiter as a comma and split the string into an array.
Syntax
Following is the syntax for the Python split() method -
str.split(separator, maxsplit)
Example
Let's look at the following example, where we are going to take the CSV string as input and we are converting it into an array using the split() method.
str1 = "Hello,Everyone,Welcome,to,Tutorialspoint" res = list(map(str.strip, str1.split(','))) print(res)
The output of the above program is as follows -
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']
Using csv.reader() Method
The Python csv.reader() method is used to read data from the CSV files. It is part of the CSV module, which provides various functions, classes, and tools that help us in reading, writing, and modifying existing CSV files.
Example
In the following example, we are going to use the csv.reader() method to convert the CSV string into an array.
import csv str1 = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA".splitlines() x = csv.reader(str1) print(list(x))
The following is the output of the above program -
[['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]