There are few methods to convert a list to string in python
1. Using join () function
It is basically joining function, which is used to join the two or more strings in python or to concatenate a list of characters can be joined using the join function.
For example
stng = ""
stng1 = ("gaon", "gore", "Gaon")
print (stng.join(stng1))
Output:
gaongoreGaon
''.join
Convert integer
To convert different type of data to a string use str function.
mlist =[1,2,3]
print''.join(str(e) for e in mlist)
Output:
123
Specifying any type of Delimiters
Till now we have used space as a delimiter, but you can use any type of elements to separate in new string. Here we are using '-' (hyphen).
mlist =['1','2','3']
print'-'.join(str(e) for e in mlist)
Output:
1-2-3
Specify to Some Extent of Range
In some of the cases we are required not to change the whole string but half of string or to some extent, in that case, we specify the range to be changed
Here we are using Range of two elements.
mlist =['1','2','3','4']
print'-'.join(str(e) for e in mlist[:2])
Output:
1-2
Join(list) - String Method
Using “”.join(list):- it takes a list and join in a string. It is called string method.
Note: If the list contains strings then it joins them.
Example:
m_lst = ["Mumbai ", "is ", "a city"]
print "".join(m_lst) ## python 3 does not support it
Output
Mumbai is a city
Using ''.join(map())
In case of number list another function can map() also can be used to convert into string and join.
m_lst = [90, 88, 65, 64]
print "".join(map(str, m_lst)) ## python 3 does not support it
Output will be
90 88 65 64
2. Traversal of list Function
A list of characters initialize at starting, and traverse to all characters in the list, indexed and all collected to frame a string. As the traverse is completed the string is printed.
Examples:
# program to convert a list of charcater to a string
def convert(characters):
# initialization of string to ""
new_char = ""
# traverse in the string
for x in characters:
new_char += x
# return string
return new_char
# driver code
characters = ['I', 'n', 'd', 'i', 'a ', ' i', 's', ' a ', 'g', 'r', 'e', 'a', 't']
print(convert(characters))
Output of the program will be
India is a great