Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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中使用字符串连接函数时?_Python_String - Fatal编程技术网

“如何跳过”\";在Python中使用字符串连接函数时?

“如何跳过”\";在Python中使用字符串连接函数时?,python,string,Python,String,例如,我这里有代码: string_list = ['a', 'b', 'c\n', 'd', 'e', 'f'] print(' '.join(string_list)) 输出将是: a b c d e f 如何获得以下结果: a b c d e f 相反?这似乎有效: string_list = ['a', 'b', 'c\n', 'd', 'e', 'f'] output = "".join(x + " " if not "\n" in x else x for x in str

例如,我这里有代码:

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']
print(' '.join(string_list))
输出将是:

a b c
 d e f
如何获得以下结果:

a b c
d e f
相反?

这似乎有效:

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']

output = "".join(x + " " if not "\n" in x else x for x in string_list)[:-1]

print(output)
输出:

a b c
d e f


正如@wjandrea指出的,我们可以使用
s if s.endswith('\n')else s+''表示字符串列表中的s,而不是使用
x+''if not“\n”表示字符串列表中的x。如果x[-1]=“\n”else x+”,我们也可以使用
x作为字符串列表中的x
。两者都有点干净。

如果完全忽略
join
,这很简单

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']
output = ""
for string in string_list:
    output += string + (" " if not string.endswith("\n") else "")
output = output.rstrip() # If you don't want a trailing " ".

谢谢大家回答我的问题。我自己想出了一个解决办法:

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']
joined_string = ' '.join(string_list)
print(joined_string.replace('\n ', '\n'))

它起作用了

这回答了你的问题吗?这是什么背景?看起来很尴尬,不是吗?很抱歉没有背景。。。我只是在学习Python和玩Jupyter笔记本…没关系,别担心,我只是好奇而已。这是一个玩具示例?是的,我正在尝试join()函数,并尝试添加“\n”只是为了好玩,因为它会留下一个尾随的
:)我可以找到一个非常类似的生成器,但我认为它更清楚一些:
s如果s.endswith('\n')else s+''表示字符串列表中的s(
@wjandrea谢谢:)这将删除
“\n”
同样,OP在其所需输出中显示了这一点……感谢您的回答。但是当应用rstrip()时,文本“def”不会进入新行。我认为这段代码在添加
.rstrip()
之前就已经工作了。