Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a list into a string with spaces in Python?

How can I convert a list into a space-separated string in Python?

For example, I want to convert this list:

my_list = [how,are,you] 

Into the string "how are you"

The spaces are important. I don't want to get howareyou as I have with my attempt so far of using

"".join(my_list) 
like image 623
user1653402 Avatar asked Sep 06 '12 23:09

user1653402


People also ask

How do you convert a list to a space-separated string?

To convert a list into a space-separated string: Call the join() method on a string that contains a space. Pass the list to the join() method. The method will return a space-separated string.

How do you print a list as space-separated integers in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

Can strings have spaces in Python?

Per W3 schools: A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

How do I print a list as a string?

The most pythonic way of converting a list to string is by using the join() method. The join() method is used to facilitate this exact purpose. It takes in iterables, joins them, and returns them as a string. However, the values in the iterable should be of string data type.


1 Answers

" ".join(my_list) 

You need to join with a space, not an empty string.

like image 152
Joran Beasley Avatar answered Oct 12 '22 14:10

Joran Beasley