Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate python string from list entries [duplicate]

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.

like image 749
veda905 Avatar asked Apr 10 '15 16:04

veda905


People also ask

How do you concatenate strings from a list in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I combine strings within a list?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

What is the best way to concatenate strings in Python?

One of the most popular methods to concatenate two strings in Python (or more) is using the + operator. The + operator, when used with two strings, concatenates the strings together to form one.


1 Answers

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?'
like image 95
Martijn Pieters Avatar answered Sep 30 '22 08:09

Martijn Pieters