use*_*402 74 python string spaces list
如何在Python中将列表转换为以空格分隔的字符串?
例如,我想转换此列表:
my_list = [how,are,you]
Run Code Online (Sandbox Code Playgroud)
进入字符串 "how are you"
空间很重要.我不想得到howareyou我迄今为止使用的尝试
"".join(my_list)
Run Code Online (Sandbox Code Playgroud)
Jor*_*ley 158
" ".join(my_list)
Run Code Online (Sandbox Code Playgroud)
你需要加入空格而不是空字符串......
小智 13
我会把它作为一种替代方案,只是为了它,尽管与" ".join(my_list)字符串相比它几乎没用.对于非字符串(例如int的数组),这可能更好:
" ".join(str(item) for item in my_list)
Run Code Online (Sandbox Code Playgroud)
小智 5
因此,为了达到预期的输出,我们首先应该了解该功能是如何工作的。
python 文档中描述的方法语法join()如下:
string_name.join(iterable)
需要注意的事项:
string与 的元素连接的iterable。元素之间的分隔符是string_name。iterable都会引发TypeError现在,要添加空格,我们只需要将 a 替换string_name为 a" "或 a ,' '它们都可以工作并放置iterable我们想要连接的 a 。
所以,我们的函数看起来像这样:
' '.join(my_list)
Run Code Online (Sandbox Code Playgroud)
white spaces但是,如果我们想在 中的元素之间添加特定数量的 in 该怎么办iterable?
我们需要添加这个:
str(number*" ").join(iterable)
Run Code Online (Sandbox Code Playgroud)
这里,number是用户输入。
因此,例如如果number=4.
然后, 的输出str(4*" ").join(my_list)将为how are you,因此每个单词之间有 4 个空格。