Python list to string with separators

How do I convert a list into a string with spaces in Python?

How can I convert a list into a space-separated string in Python? For example, I want to convert this list:

6 Answers 6

You need to join with a space, not an empty string.

what if we have string in this format list = [‘how ‘, ‘are ‘, ‘you ‘] then how to convert this into list.

I’ll throw this in as an alternative just for the heck of it, even though it’s pretty much useless when compared to » «.join(my_list) for strings. For non-strings (such as an array of ints) this may be better:

" ".join(str(item) for item in my_list) 

For Non String list we can do like this as well

So in order to achieve a desired output, we should first know how the function works.

The syntax for join() method as described in the python documentation is as follows:

  • It returns a string concatenated with the elements of iterable . The separator between the elements being the string_name .
  • Any non-string value in the iterable will raise a TypeError

Now, to add white spaces, we just need to replace the string_name with a » » or a ‘ ‘ both of them will work and place the iterable that we want to concatenate.

Читайте также:  Str replace php кириллица

So, our function will look something like this:

But, what if we want to add a particular number of white spaces in between our elements in the iterable ?

here, the number will be a user input.

So, for example if number=4 .

Then, the output of str(4*» «).join(my_list) will be how are you , so in between every word there are 4 white spaces.

Источник

Creating comma-separated string from list [duplicate]

How do I create the string? I could manually convert every element from int to string, insert this into a new list, and then do the join on this new list, but I’m wondering if there is a cleaner solution.

the str.join answer is OK if your list is guaranteed to have only integers — for anything serious use the csv module, it will handle a lot of corner cases.

3 Answers 3

str.join only accepts an iterable of strings, not one of integers. From the docs:

str.join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable .

Thus, you need to convert the items in x into strings. You can use either map or a list comprehension:

x = [3, 1, 4, 1, 5] y = ",".join(map(str, x)) x = [3, 1, 4, 1, 5] y = ",".join([str(item) for item in x]) 

See a demonstration below:

>>> x = [3, 1, 4, 1, 5] >>> >>> ",".join(map(str, x)) '3,1,4,1,5' >>> >>> ",".join([str(item) for item in x]) '3,1,4,1,5' >>> 

@IoannisFilippidis — Using a list comprehension is more efficient with str.join . See here for details: stackoverflow.com/a/9061024/2555451

Very interesting, thank you for noting this. I think it would make a valuable addition to the answer.

If you are dealing with a csv file that is something other than the trivial example here, please do remember you are better off using the csv module to read and write csv, since CSV can be surprisingly complex.

import csv x = [['Header\n1', 'H 2', 'H 3', 'H, 4'],[1,2,3,4],[5,6,7,8],[9,10,11,12]] with open('/tmp/test.csv', 'w') as fout: writer=csv.writer(fout) for l in x: writer.writerow(l) 

Note the embedded comma in ‘H, 4’ and the embedded new line in ‘Header\n1’ that may trip up efforts to decode if not properly encoded.

The file ‘test.csv’ that the csv module produces:

"Header 1",H 2,H 3,"H, 4" 1,2,3,4 5,6,7,8 9,10,11,12 

Note the quoting around «Header\n1» and «H, 4″` in the file so that the csv is correctly decoded in the future.

Now check you can read that back:

with open('/tmp/test.csv') as f: csv_in=[[int(e) if e.isdigit() else e for e in row] for row in csv.reader(f)] >>> csv_in==x True 

Just sayin’ You are usually better off using the tools in the library for csv.

Источник

How would you make a comma-separated string from a list of strings?

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, [‘a’, ‘b’, ‘c’] to ‘a,b,c’ ? (The cases [‘s’] and [] should be mapped to ‘s’ and » , respectively.) I usually end up using something like ».join(map(lambda x: x+’,’,l))[:-1] , but also feeling somewhat unsatisfied.

15 Answers 15

my_list = ['a', 'b', 'c', 'd'] my_string = ','.join(my_list) 

This won’t work if the list contains integers

And if the list contains non-string types (such as integers, floats, bools, None) then do:

my_string = ','.join(map(str, my_list)) 

Note if you are using python 2.7 (which you shouldn’t by now) then using str will raise an exception if any item in the list has unicode.

My requirement, bringing me here, was to fill an SQL «WHERE x NOT IN ()» clause. The join() function will insert any string you like between elements but does nothing for each end of the list. So this works: nameString = ‘»<>«‘.format(‘», «‘.join(nameList)) Those are single quotes enclosing the desired double quoted strings. Python 3.7

It’s worth noting that this answer was posted over 13 years ago. I’m guessing plenty has changed with Python since then.

Why the map / lambda magic? Doesn’t this work?

>>> foo = ['a', 'b', 'c'] >>> print(','.join(foo)) a,b,c >>> print(','.join([])) >>> print(','.join(['a'])) a 

In case if there are numbers in the list, you could use list comprehension:

or a generator expression:

«,».join(l) will not work for all cases. I’d suggest using the csv module with StringIO

import StringIO import csv l = ['list','of','["""crazy"quotes"and\'',123,'other things'] line = StringIO.StringIO() writer = csv.writer(line) writer.writerow(l) csvcontent = line.getvalue() # 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n' 

Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I’d expect generator expressions to be preferred to imap.

>>> l = [1, "foo", 4 ,"bar"] >>> ",".join(str(bit) for bit in l) '1,foo,4,bar' 

Experts, please, tell why isn’t this upvoted as the best solution? It works with integers, strings (with ‘crazy characters’ as well) and it’s just 1 line of code. I’m newbie, so I’d like to know the limitations of this method.

Here is a alternative solution in Python 3.0 which allows non-string list items:

>>> import io >>> s = io.StringIO() >>> print(*alist, file=s, sep=', ', end='') >>> s.getvalue() "a, 1, (2, 'b')" 

NOTE: The space after comma is intentional.

Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:

>>> my_list = ['A', '', '', 'D', 'E',] >>> ",".join([str(i) for i in my_list if i]) 'A,D,E' 

my_list may contain any type of variables. This avoid the result ‘A. D,E’ .

l=['a', 1, 'b', 2] print str(l)[1:-1] Output: "'a', 1, 'b', 2" 

I think you should point out that unlike the other solutions on this page, you quote strings as well.

@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator

from itertools import imap l = [1, "foo", 4 ,"bar"] ",".join(imap(str, l)) 

This solution doesn’t fulfill the requirements of not adding extra comma for empty string and adding a ‘None’ with NoneType.

Here is an example with list

>>> myList = [['Apple'],['Orange']] >>> myList = ','.join(map(str, [i[0] for i in myList])) >>> print "Output:", myList Output: Apple,Orange 
>>> myList = [['Apple'],['Orange']] >>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) >>> print "Output:", myList Output: Apple,Orange 
myList = ['Apple','Orange'] myList = ','.join(map(str, myList)) print "Output:", myList Output: Apple,Orange 

If you want to do the shortcut way 🙂 :

','.join([str(word) for word in wordList]) 

But if you want to show off with logic 🙂 :

wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD'] stringText = '' for word in wordList: stringText += word + ',' stringText = stringText[:-2] # get rid of last comma print(stringText) 

Unless I’m missing something, ‘,’.join(foo) should do what you’re asking for.

>>> ','.join(['']) '' >>> ','.join(['s']) 's' >>> ','.join(['a','b','c']) 'a,b,c' 

(edit: and as jmanning2k points out,

is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas — at that point, you need the full power of the csv module, as Douglas points out in his answer.)

I would say the csv library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.

To output a list l to a .csv file:

import csv with open('some.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(l) # this will output l as a single row. 

It is also possible to use writer.writerows(iterable) to output multiple rows to csv.

This example is compatible with Python 3, as the other answer here used StringIO which is Python 2.

l = ["foo" , "baar" , 6] where_clause = ". IN ("+(','.join([ f"''" for x in l]))+")" >> ". IN ('foo','baar','6')" 

My two cents. I like simpler an one-line code in python:

>>> from itertools import imap, ifilter >>> l = ['a', '', 'b', 1, None] >>> ','.join(imap(str, ifilter(lambda x: x, l))) a,b,1 >>> m = ['a', '', None] >>> ','.join(imap(str, ifilter(lambda x: x, m))) 'a' 

It’s pythonic, works for strings, numbers, None and empty string. It’s short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:

Also this solution doesn’t create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).

Источник

Convert List to Comma-Separated String in Python

Convert List to Comma-Separated String in Python

  1. Use the join() Function to Convert a List to a Comma-Separated String in Python
  2. Use the StringIO Module to Convert a List to a Comma-Separated String in Python

We can use a list to store different elements under a common name. A string is a collection of characters.

We will convert a list to a comma-separated string in this tutorial.

Use the join() Function to Convert a List to a Comma-Separated String in Python

The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.

To create a comma-separated string, we will use the comma as the separator.

lst = ['c','e','a','q'] s = ",".join(lst) print(s) 

The above method is only limited to a list containing strings.

We can use list comprehension and the str() function to work with a list containing integers or other elements. With list comprehension, we can iterate over the elements easily in a single line using the for loop, and convert each element to a string using the str() function.

We implement this in the following code.

lst = [8,9,4,1] s = ",".join([str(i) for i in lst]) print(s) 

We can also eliminate list comprehension by using the map() function. The map() function can be used to convert all elements of the list to a string by applying the str() function to every element.

lst = [8,9,4,1] s = ",".join(map(str,lst)) print(s) 

Use the StringIO Module to Convert a List to a Comma-Separated String in Python

The StringIO object is similar to a file object but in memory to work with texts. In Python 2, it can be imported directly using the StringIO module. In Python 3, it was stored in the io module.

We can use the csv.writerow() function to write the list as a comma-separated row for a CSV file in the StringIO object. For this, we need to instantiate a csv.writer object first. We can then store the contents of this object in a string using the getvalue() function.

import io import csv lst = [8,9,4,1] s_io = io.StringIO() writer = csv.writer(s_io) writer.writerow(lst) s = s_io.getvalue() print(s) 

We can also use the print() function with the unpack operator. The unpack operator * unpacks all the elements of an iterable, and stores it in the StringIO object using the file parameter in the print() function.

import io lst = [8,9,4,1] s_io = io.StringIO() print(*lst, file=s_io, sep=',', end='') s = s_io.getvalue() print(s) 

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

Related Article — Python List

Related Article — Python String

Copyright © 2023. All right reserved

Источник

Оцените статью