Solving problem is about exposing yourself to as many situations as possible like How to concatenate items in a list to a single string? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to concatenate items in a list to a single string?, which can be followed any time. Take easy to follow this discuss.
Is there a simpler way to concatenate string items in a list into a single string? Can I use the
E.g. this is the input
['this','is','a','sentence'] and this is the desired output
sentence = ['this','is','a','sentence'] sent_str = "" for i in sentence: sent_str += str(i) + "-" sent_str = sent_str[:-1] print sent_str
'this', 'is', 'a', 'sentence'] '-'.join(sentence) 'this-is-a-sentence' ' '.join(sentence) 'this is a sentence'sentence = [
A more generic way to convert python lists to strings would be:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10] my_lst_str = ''.join(map(str, my_lst)) print(my_lst_str) '12345678910'my_lst = [
It’s very useful for beginners to know
why join is a string method.
It’s very strange at the beginning, but very useful after this.
The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).
.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).
Once you learn it, it’s very comfortable and you can do tricks like this to add parentheses.
",".join("12345").join(("(",")")) Out: '(1,2,3,4,5)' list = ["(",")"] ",".join("12345").join(list) Out: '(1,2,3,4,5)'
Edit from the future: Please don’t use this, this function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although @Burhan Khalid’s answer is good, I think it’s more understandable like this:
from str import join sentence = ['this','is','a','sentence'] join(sentence, "-")
The second argument to join() is optional and defaults to ” “.
We can specify how we have to join the string. Instead of ‘-‘, we can use ‘ ‘
sentence = ['this','is','a','sentence'] s=(" ".join(sentence)) print(s)
We can also use Python’s reduce function:
from functools import reduce sentence = ['this','is','a','sentence'] out_str = str(reduce(lambda x,y: x+"-"+y, sentence)) print(out_str)
list = ['aaa', 'bbb', 'ccc'] string = ''.join(list) print(string) aaabbbccc string = ','.join(list) print(string) aaa,bbb,ccc string = '-'.join(list) print(string) aaa-bbb-ccc string = 'n'.join(list) print(string) aaa bbb ccc
This will help for sure –
arr=['a','b','h','i'] # let this be the list s="" # creating a empty string for i in arr: s+=i # to form string without using any function print(s)