“如何跳过”\";在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()
之前就已经工作了。