Suppose you have a python list containing some string values and you want a single string composed of all the items of list.
This article will guide you to the solution.
List to string
In order to convert a list consisting of string items to a string, join
method of string class is used. join()
method takes a single argument which should be an iterable, meaning something that can be iterated such as a list and returns a string which is the combination of all items in that iterable separated by the string on which join()
is called.
Thus we will be calling it on an empty string. This way all items of the list will be joined by an empty string. Complete example follows.
# initialize a list of strings dummy_list = ["codippa", "the", "website"] # call join on empty string passing it the list list_values = "".join(dummy_list) # print the result print("Combination of list values = " +list_values)
Output
Combination of list values = codippathewebsite
List to comma separated string
In the above example, we merged the items of the list using an empty string.
This is because join()
method combines the items of the list with the string it is called on.
Therefore, if want a string which is the combination of list items separated by a comma, we can do it by calling join()
on a comma(as a string) so that it returns a string with the combination of list items separated by a comma.
# initialize a list of strings dummy_list = ["codippa", "the", "website"] # call join on a comma as string passing it the list list_values = ",".join(dummy_list) # print the result print("Combination of list values = " +list_values)
Output
Combination of list values = codippa,the,website
Similarly, we can combine a list into a single string with list items separated by a particular character(such as – + , etc.), we need to call join
method in that character passing it the list of items.
Non-string list to string
Both the above examples dealt with a list which had all the items as a string.
If the items of the list are not strings, we need to convert each item to a string using str()
or repr()
methods which return string representation of the value passed to them.
Each list item needs to be converted separately so we need to loop over the list.
Complete example is given below.
# initialize a list of integers dummy_list = [1,2,3] # iterate over the list and # call join on empty string passing it list item converted to a string list_values = "".join(str(list_item) for list_item in dummy_list) # print the result print("Combination of list values = " +list_values)
Above code iterates over the list of integers using a for
loop converting each item into a string using str
method and passing it to join
method. Resultant output is
Combination of list values = 123
If you are unfamiliar with loops, refer this link in out tutorials section.