19

Lets say that I have a list of strings that I would like to jam together into a single string separated by underscores. I know I can do this using a loop, but python does a lot of things without loops. Is there something in python that already has this functionality? For example I have:

string_list = ['Hello', 'there', 'how', 'are', 'you?']

and I want to make a single string like:

'Hello_there_how_are_you?'

What I have tried:

mystr = ''    
mystr.join(string_list+'_')

But this gives a "TypeError: can only concatenate list (not "str") to list". I know its something simple like this, but its not immediately obvious.

veda905
  • 782
  • 2
  • 12
  • 32

2 Answers2

35

You use the joining character to join the list:

string_list = ['Hello', 'there', 'how', 'are', 'you?']
'_'.join(string_list)

Demo:

>>> string_list = ['Hello', 'there', 'how', 'are', 'you?']
>>> '_'.join(string_list)
'Hello_there_how_are_you?'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Got it I used:

mystr+'_'.join(string_list)
'Hello_there_how_are_you?'

I wanted to use the join function from the string, not the list. Seems obvious now.

veda905
  • 782
  • 2
  • 12
  • 32