Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to paste a list to a string in python?

I want to do something similar to R’s paste function. For example,

> paste("a", "b", "c", sep = ",")
[1] "a,b,c"

In Python, I can do

''.join(i + ',' for i in ['a', 'b', 'c'])
#'a,b,c,'

However, I don’t want the last comma. Is there a more convenient way to convert the list to a string?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can pass in any iterable into str.join. There is no need for the generator expression.

https://docs.python.org/3/library/stdtypes.html#str.join

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

','.join(['a', 'b', 'c']) returns 'a,b,c'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading