1

I have a list with some text:

my_list = ['sentence1','sentence2','sentence3','sentence4' ]

And I want as output a string like this:

'sentence1, sentence2, sentence3, sentence4'

If I make this, I get an aditional ', ' at the end

string_sentences = ''
for sentence in my_list:
    string_sentences +=  sentence +', '
string_sentences

output: 'sentence1, sentence2, sentence3, sentence4, '

same with this approach, but now at the beginning:

string_sentences = ''
for sentence in my_list:
    string_sentences += ', ' + sentence 
string_sentences

', sentence1, sentence2, sentence3, sentence4'

Only thing I can think to solve it is to keep track of the indices

string_sentences = ''
for i,sentence in enumerate(my_list):
    if i +1 < len(my_list):
        string_sentences += sentence +', '
    else:
        string_sentences += sentence
string_sentences

ouput: 'sentence1, sentence2, sentence3, sentence4'

But this seems like a very common issues, and I wonder whether is a more pythonic way to solve it.

Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181
  • 1
    Your suggested way is the only way to do this nicely in many languages (apart from having a boolean variable `firstTime` which is set to `False` after the first loop), apparently. In Python, you have `join` method as suggested in the answer. – justhalf Apr 06 '16 at 03:04
  • 1
    @justhalf actually join is a common way to do this in [Java 8](http://stackoverflow.com/questions/24053499/java-8-string-join-operation-has-significant-performance-impact), [Perl](http://perldoc.perl.org/functions/join.html), and [C#](http://stackoverflow.com/questions/21078/most-effecient-way-to-concatenate-strings) (though stringbuilder may be used for larger values) as well – LinkBerest Apr 06 '16 at 03:28
  • I was not aware that they have `join` methods in Perl and C#, but at least in Java, it was a features quite late to be added (Java 8 is still considered new for me) – justhalf Apr 06 '16 at 03:34

2 Answers2

4

Use the join method to convert your list to a string. Provide a separator that will go between each element that is extracted from the list that goes in to your string. In this case , and a space ' ' after the comma:

my_list = ['sentence1','sentence2','sentence3','sentence4' ]
s = ', '.join(my_list)

By printing s we will have:

'sentence1, sentence2, sentence3, sentence4'

Just some extra notes about why using join here would actually be preferable, is because it actually runs at C speed as opposed to the speed you get from a Python loop. Read about performance tips here.

Finally, a warning when doing this. The join always expects an iterable of strings. Which means, if you have a list of integers [1, 2, 3, 4]. You will not be able to call join directly on this. You would have to cast each of those values to an str. A simple example would be something like this:

list_of_ints = [1, 2, 3, 4]
', '.join([str(n) for n in list_of_ints])

So, to further explain what just happened in the above example. Since we actually have a list of integers. In order to successfully create our string from that list, we need to cast each element in the list to a string. In order to do this, we will use a list-comprehension to create this list of string integers, and then call your join method.

Now, the reason why we are actually not using a generator expression here and using a list comprehension, is because in fact the join method will actually scan the iterable twice, therefore the comprehension in this case is actually faster.

This is actually very nicely explained here.

Community
  • 1
  • 1
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • Thanks, about the 'join(str(n) for n in list_of_ints)' what is getting the join mehod from 'str(n) for n in list_of_ints'? why isn't needed to put it as a list comprehension or a generator join([str(n) for n in list_of_ints])? – Luis Ramon Ramirez Rodriguez Apr 06 '16 at 03:25
  • 1
    @LuisRamonRamirezRodriguez I'm glad you asked that question. I am updating my answer to give you exactly that answer. – idjaw Apr 06 '16 at 03:26
  • 1
    @LuisRamonRamirezRodriguez Take a look at the updated answer. – idjaw Apr 06 '16 at 03:36
1

Is this what you want?

>>> my_list = ['sentence1','sentence2','sentence3','sentence4' ]
>>> ', '.join(my_list)
'sentence1, sentence2, sentence3, sentence4'
>>> 
>>> result = ', '.join(my_list)
>>> result
'sentence1, sentence2, sentence3, sentence4'
>>> 
joel goldstick
  • 4,393
  • 6
  • 30
  • 46
  • 2
    Don't use answers to ask a question: be more assertive! – PM 2Ring Apr 06 '16 at 03:16
  • 2
    I strongly suggest that you modify that wording: some users (especially those that spend a lot of time in the review queues) will downvote or flag answers that start with a clarification question. – PM 2Ring Apr 06 '16 at 04:01