Concatenate python string from list entries [dupli

2020-07-03 06:59发布

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.

2条回答
Evening l夕情丶
2楼-- · 2020-07-03 07:59

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?'
查看更多
够拽才男人
3楼-- · 2020-07-03 08:05

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.

查看更多
登录 后发表回答