拆分后如何用逗号连接字符串:Python

时间:2018-09-07 14:41:19

标签: python-3.x

我有一个函数,用逗号分割字符串,每次分割都会执行一些功能,并返回所有结果。我希望结果再次用逗号返回

示例

original_string ="five, negative four, three"

我在上面运行了一些功能,然后得到

def challenge1(original_string):
    #some code
    return new_string

我尝试过

print(new_string.splitlines())
#below is what I get. How can I get them on the same line to start with so I add commas to them later
['5']
['-4']
['3']

以下是我得到的结果

5 
-4
3  

我需要的结果是

5, -4, 3

我一直在尝试使用.join(", ")的许多选项,但它仍然返回新行,我如何获得上述结果

2 个答案:

答案 0 :(得分:1)

您应该使用列表作为参数调用str.join()方法:

", ".join('5\n-4\n3\n'.splitlines())

这将返回'5, -4, 3'

这意味着您的challenge1函数的return语句应改为:

return ", ".join(new_string.splitlines())

答案 1 :(得分:0)

嗯,这比我想象的要容易

def challenge1(original_string):
    #some code
    return new_string

print(new_string, end=", ")