简体   繁体   English

在换行前删除空格

[英]Remove spaces before newlines

I need to remove all spaces before the newline character throughout a string. 我需要删除整个字符串中的换行符之前的所有空格。

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

output: 输出:

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)

Edit: better version from comments: 编辑:评论的更好版本:

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

As you can find here , 你可以在这里找到,

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join: 要删除所有空白字符(空格,制表符,换行符等),您可以使用拆分然后加入:

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

or a regular expression: 或正则表达式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用换行符打印但没有空格 - Printing with newlines but no empty spaces 在字母前后删除字符串中的空格 - Remove spaces from string after and before letter 如何将文本文件制作成数组列表(数组中的数组)并删除空格/换行符 - How to make a text file into a list of arrays (array-in-array) and remove spaces/newlines 需要帮助加入字典项目并删除换行符和多个空格和特殊字符 - Need help joining dictionary items and remove newlines and multiple spaces and special characters 在Python中删除开头/结尾和内部多个空格,但不删除制表符,换行符或返回字符 - Remove leading/ending and internal multiple spaces but NOT tabs, newlines, or return characters, in Python 去除空格/制表符/换行符-python - Strip spaces/tabs/newlines - python 删除美丽汤中的换行符 - Remove newlines in beautiful soup 如何在没有正则表达式的情况下删除 python 中逗号前的空格? - How can I remove spaces before commas in python without regexes? 如何仅删除出现在数字之后和带有 RegEx 的字母之前的空格? - How to remove only the spaces that occur after a digit, and before a letter with RegEx? 在 python 文件中查找所有空格、换行符和制表符 - find all spaces, newlines and tabs in a python file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM