Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在拆分后用逗号连接字符串:Python_Python 3.x - Fatal编程技术网

Python 3.x 如何在拆分后用逗号连接字符串:Python

Python 3.x 如何在拆分后用逗号连接字符串:Python,python-3.x,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

我有一个函数,它在逗号上拆分字符串,在每次拆分时执行一些函数并返回所有结果。我希望再次返回带有逗号的结果

示例

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(“,”
尝试了很多选项,但它仍然返回一行新行,如何获得上述结果您应该调用
str.join()
方法,并使用列表作为参数:

", ".join('5\n-4\n3\n'.splitlines())
这将返回
'5、-4、3'

这意味着
challenge1
函数的返回语句应该是:

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

这比我想象的要容易

def challenge1(original_string):
    #some code
    return new_string

print(new_string, end=", ")

返回新的_字符串“,”.join('5\n-4\n3\n'.splitlines())这不是应用我建议的方式。我用一个例子更新了我的答案,说明了如何修改函数的返回语句。
['、5']['、-4']['、3']
它们都在新行中,而不是在同一行中。如果有帮助,则结果在之前由forloop生成,并在
new\u string