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)
" ".join(my_list)
you need to join with a space not an empty string ...
I'll throw this in as an alternative just for the heck of it, even though it's pretty much useless when compared to " ".join(my_list) for strings. For non-strings (such as an array of ints) this may be better:
" ".join(str(item) for item in my_list)
For Non String list we can do like this as well
" ".join(map(str, my_list))
So in order to achieve a desired output, we should first know how the function works.
The syntax for join() method as described in the python documentation is as follows:
string_name.join(iterable)
Things to be noted:
- It returns a
stringconcatenated with the elements ofiterable. The separator between the elements being thestring_name. - Any non-string value in the
iterablewill raise aTypeError
Now, to add white spaces, we just need to replace the string_name with a " " or a ' ' both of them will work and place the iterable that we want to concatenate.
So, our function will look something like this:
' '.join(my_list)
But, what if we want to add particular number of white spaces in between our elements in the iterable ?
we just need to do this:
str(number*" ").join(iterable)
here the number will be a user input.
So, for example if number=4.
Then, the output of str(4*" ").join(my_list) will be how are you, so in between every word there are 4 white spaces.
Why don't you add a space in the items of the list itself, like :list = ["how ", "are ", "you "]
来源:https://stackoverflow.com/questions/12309976/how-do-i-convert-a-list-into-a-string-with-spaces-in-python