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.
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.
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.
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.
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?'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With