0

I am trying to join the following array into a proper csv line (not a file)

#input array

x = [2,"Appple", "car,plane",45.2]

I tried the following

",".join(x)

But it fails as the resulting output is 2,Apple,car,plane,45.2 . It also fails due to the numbers and floats.

Expected result would be:

2,Apple,"car,plane",45.2
Ashok Gj
  • 168
  • 1
  • 9
  • Have you tried using the [`csv` module](https://docs.python.org/3/library/csv.html)…? – deceze Jun 09 '22 at 09:13
  • It is not clear what is the difference between "resulting output" and "expected result". – Gino Mempin Jun 09 '22 at 09:14
  • 1
    @Gino The missing quotes. – deceze Jun 09 '22 at 09:14
  • "car,plane" is a single string, the resulting output treats them as separate. The expected one still treats it as a single string as it is enclosed in double quotes – Ashok Gj Jun 09 '22 at 09:16
  • 1
    You can also extend your approach slightly to work for your toy example if that is the only thing you care about: `",".join([f'"{i}"' if ',' in str(i) else str(i) for i in x])` – HansQ Jun 09 '22 at 09:25

2 Answers2

0

The code above will output the following string: z= "2, 'Appple', 'car,plane', 45.2"

x = [2, "Appple", "car,plane", 45.2]
z = f"{x}"
z = z.replace("[","")
z = z.replace("]", "")
Moritz Hartmann
  • 140
  • 1
  • 10
  • My understanding of the question is that he wish to have a string which can then be inserted in the .csv. The code above will output a `z= "2, 'Appple', 'car,plane', 45.2" ` – Moritz Hartmann Jun 09 '22 at 10:26
-1

A simple approach would be using pandas: pd.DataFrame(x).to_csv(). Or using the csv module:

import csv
import io

out = io.StringIO()
writer = csv.writer(out) 
writer.writerow(x)
csv_string = out.getvalue()
out.close()
HansQ
  • 380
  • 1
  • 7
  • Where "simple" means "include a giant dependency"… – deceze Jun 09 '22 at 09:15
  • @deceze and why is that a problem? Is he going to distribute his novel list to csv conversion package? – HansQ Jun 09 '22 at 09:16
  • 1
    This functionality is natively available in the `csv` module, even if it may be two more lines of code… – deceze Jun 09 '22 at 09:19
  • While that may be the case, it is not uncommon that somebody already has pandas installed or doesn't care installing it. – HansQ Jun 09 '22 at 09:23