简体   繁体   English

如何将列表转换为 Python 中带空格的字符串?

[英]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?如何将列表转换为 Python 中以空格分隔的字符串?

For example, I want to convert this list:例如,我想转换这个列表:

my_list = ["how", "are", "you"]

into the string "how are you" .进入字符串"how are you"

The spaces are important.空格很重要。 I don't want to get "howareyou" .我不想得到"howareyou"

" ".join(my_list)

你需要加入一个空格而不是一个空字符串......

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.我将把它作为替代方案,只是为了它,即使与字符串的" ".join(my_list)相比它几乎没用。 For non-strings (such as an array of ints) this may be better:对于非字符串(例如整数数组),这可能更好:

" ".join(str(item) for item in my_list)

对于非字符串list我们也可以这样做

" ".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: python 文档中描述的join()方法的语法如下:

string_name.join(iterable)

Things to be noted:需要注意的事项:

  • It returns a string concatenated with the elements of iterable .它返回一个与iterable元素连接的string The separator between the elements being the string_name .元素之间的分隔符是string_name
  • Any non-string value in the iterable will raise a TypeError iterable中的任何非字符串值都会引发TypeError

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.现在,要添加空格,我们只需要将string_name替换为" "' ' ,它们都可以工作并放置我们想要连接的iterable

So, our function will look something like this:所以,我们的函数看起来像这样:

' '.join(my_list)

But, what if we want to add a particular number of white spaces in between our elements in the iterable ?但是,如果我们想在iterable的元素之间添加特定数量的white spaces怎么办?

We need to add this:我们需要添加这个:

str(number*" ").join(iterable)

here, the number will be a user input.在这里, number将是用户输入。

So, for example if number=4 .因此,例如如果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.然后, str(4*" ").join(my_list)将是how are you ,因此在每个单词之间有 4 个空格。

"".join([i for i in my_list])

这应该像你问的那样工作!

you can iterate through it to do it你可以遍历它来做到这一点

my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
    my_string = my_string + ' ' + a
print(my_string)

output is输出是

 how are you

you can strip it to get你可以把它剥离得到

how are you

like this像这样

my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
    my_string = my_string + ' ' + a
print(my_string.strip())

为什么不在列表本身的项目中添加一个空格,例如:
list = ["how ", "are ", "you "]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM