18

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.

0

2 Answers 2

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?'
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

You don't need to use mystr at all here; it is just an empty string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.