无法使用Python删除字符串上的空白
我正试图消除这个列表上的空白,但我无法做到。有人知道我的代码哪里出错了吗无法使用Python删除字符串上的空白,python,whitespace,Python,Whitespace,我正试图消除这个列表上的空白,但我无法做到。有人知道我的代码哪里出错了吗 love_maybe_lines = ['Always ', ' in the middle of our bloodiest battles ', 'you lay down your arms', ' like flowering mines ', ' to conquer me home. '] love_maybe_lines_joined =
love_maybe_lines = ['Always ', ' in the middle of our bloodiest battles ', 'you lay down your arms', ' like flowering mines ', ' to conquer me home. ']
love_maybe_lines_joined = '\n'.join(love_maybe_lines)
love_maybe_lines_stripped = love_maybe_lines_joined.strip()
print(love_maybe_lines_stripped)
Terminal:
Always
in the middle of our bloodiest battles
you lay down your arms
like flowering mines
to conquer me home.
这可能会有帮助
这可能会有所帮助。请参阅
.strip()
的文档。它只会删除字符串开头和结尾的空格。尝试“\n”.join(映射(str.strip,love\u maybe\u line))
…因此strip
在join
之前,love\u maybe\u line的元素只在字符串的开头和结尾起作用,而不在两者之间。在加入列表项之前,您必须去除每个列表项。我认为通过“\n.join()”列表,它们在单独的行上,所以现在空格在开头和结尾?@Blenderinho“strip”不关心行,它只关心字符串作为一个整体。有关.strip()
,请参阅文档。它只会删除字符串开头和结尾的空格。尝试“\n”.join(映射(str.strip,love\u maybe\u line))
…因此strip
在join
之前,love\u maybe\u line的元素只在字符串的开头和结尾起作用,而不在两者之间。在加入列表项之前,您必须去除每个列表项。我认为通过“\n.join()”列表,它们在单独的行上,所以现在空格在开头和结尾?@Blenderinho“strip”不关心行,它只关心整个字符串。
love_maybe_lines = ['Always ', ' in the middle of our bloodiest battles ', 'you lay down your arms', ' like flowering mines ', ' to conquer me home. ']
love_maybe_lines = [item.strip() for item in love_maybe_lines]