user18349068
user18349068

Reputation:

Unable to convert list into string in python

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

Upvotes: 0

Views: 64

Answers (2)

Selcuk
Selcuk

Reputation: 59184

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'

Upvotes: 1

Doseph
Doseph

Reputation: 199

" ".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.

Upvotes: 0

Related Questions