簡體   English   中英

在換行前刪除空格

[英]Remove spaces before newlines

我需要刪除整個字符串中的換行符之前的所有空格。

string = """
this is a line       \n
this is another           \n
"""

輸出:

string = """
this is a line\n
this is another\n
"""

可以拆分串入線,采用剝離右側所有空格rstrip ,然后在每行的末尾添加一個新行:

''.join([line.rstrip()+'\n' for line in string.splitlines()])
import re
re.sub('\s+\n','\n',string)

編輯:評論的更好版本:

re.sub(r'\s+$', '', string, flags=re.M)

你可以在這里找到,

要刪除所有空白字符(空格,制表符,換行符等),您可以使用拆分然后加入:

sentence = ''.join(sentence.split())

或正則表達式:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM