How do i convert a list into a string in python?
I have tried using a for
loop but i want a simpler method to join.
Input:
['I', 'want', 4, 'apples', 'and', 18, 'bananas']
Output:
I want 4 apples and 18 bananas
CodePudding user response:
" ".join([str(x) for x in ['I', 'want', 4, 'apples', 'and', 18, 'bananas']])
would work for your example.
More generally, " ".join(str(x) for x in iterable)
works.
CodePudding user response:
This is not the best method, but since you don't want to use a for
loop:
>>> ("{} " * len(my_list)).format(*my_list).strip()
'I want 4 apples and 18 bananas'
CodePudding user response:
you can try using .join() method to convert the list into the string. First you declare your List and then declare a empty string variable then use .join() method to convert.