Python join list 的意思是将一串字符串与指定的分隔符连接起来形成一个字符串。有时,当您必须将列表转换为字符串时,它很有用。例如,将字母列表转换为逗号分隔的字符串以保存在文件中。
我们可以用蟒蛇字符串join() 函数用于连接字符串列表。这个函数需要iterable
作为参数,List 是一个可交互的,所以我们可以将它与 List 一起使用。另外,列表应该包含字符串,如果您尝试加入整数列表,那么您将收到一条错误消息,如下所示TypeError: sequence item 0: expected str instance, int found
。让我们看一个在 python 中连接列表来创建字符串的简短示例。
vowels = ["a", "e", "i", "o", "u"]
vowelsCSV = ",".join(vowels)
print("Vowels are = ", vowelsCSV)
当我们运行上面的程序时,它将产生以下输出。
Vowels are = a,e,i,o,u
我们也可以使用 join() 函数来连接两个字符串。
message = "Hello ".join("World")
print(message) #prints 'Hello World'
许多 Python 开发人员都会遇到一个问题,那就是为什么 join() 函数是 String 而不是 list 的一部分。下面的语法不是更容易记住和使用吗?
vowelsCSV = vowels.join(",")
有一个流行的StackOverflow问题围绕这一点,我在这里列出了对我来说完全有意义的讨论中最重要的观点。
主要原因是join() 函数可以与任何一起使用iterable结果始终是一个 String,因此在 String API 中使用此函数比在所有可迭代类中使用它更有意义。
让我们看一个程序,我们将尝试连接具有多种数据类型的列表项。
names = ['Java', 'Python', 1]
delimiter = ','
single_str = delimiter.join(names)
print('String: {0}'.format(single_str))
Let’s see the output for this program:
This was just a demonstration that a list which contains multiple data-types cannot be combined into a single String with join()
function. List must contain only the String values.
我们可以用join()
函数也可以使用指定的分隔符分割字符串。
names = 'Python'
delimiter = ','
single_str = delimiter.join(names)
print('String: {0}'.format(single_str))
This shows that when String is passed as an argument to join() function, it splits it by character and with the specified delimiter.
除了与join()
功能,split()
函数也可用于分割字符串,其工作方式与join()
功能。我们来看一段代码:
names = ['Java', 'Python', 'Go']
delimiter = ','
single_str = delimiter.join(names)
print('String: {0}'.format(single_str))
split = single_str.split(delimiter)
print('List: {0}'.format(split))
Let’s see the output for this program:
We used the same delimiter to split the String again to back to the original list.
The split()
我们在上一个示例中演示的函数还采用可选的第二个参数,该参数表示应执行 splot 操作的次数。这是一个示例程序来演示其用法:
names = ['Java', 'Python', 'Go']
delimiter = ','
single_str = delimiter.join(names)
print('String: {0}'.format(single_str))
split = single_str.split(delimiter, 1)
print('List: {0}'.format(split))
Let’s see the output for this program:
This time, split operation was performed only one time as we provided in the split()
function parameter. That’s all for joining a list to create a string in python and using split() function to get the original list again.