使用python删除尾随空格 [英] Removing Trailing White Spaces with python

查看:41
本文介绍了使用python删除尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本在 python 中循环多个搜索/替换正则表达式,其中一个操作是删除尾随空格我试过了:

I have a script that loops over several search/replace regex in python, one of those operations is remove trailing spaces I've tried:

re.sub(r"""\s+$""", '', str)

re.sub(r""" +$""", r"""""", str)

re.sub(r""" +$""", r"""""", str, re.M)

我找到了几个简单推荐使用 strip 的答案,我的问题是我想将其集成到正则表达式替换机制中.

I found several answers that simply recommended using strip my problem is that I want to integrate this in the regex replace mechanism.

推荐答案

函数是 sub 并将目标字符串作为参数(并返回修改后的副本):

The function is sub and takes the target string as an argument (and returns a modified copy):

str = re.sub(r'\s+$', '', str)

或者如果您想从单个字符串中的多行中删除尾随空格,请使用以下方法之一:

or if you want to remove trailing spaces from multiple lines in a single string, use one of these:

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

0count 参数(其中 0 表示没有限制)然后 re.M 使$ 匹配行尾.如果您没有明确指定 flags,则需要该附加参数,因为 flags 实际上是第五个.

The 0 is the count parameter (where 0 means no limit) and then re.M makes $ match at line endings. If you don't specify flags explicitly, you need that additional parameter, because flags is actually the fifth one.

请注意,多行字符串只需要三重引号.重要的是模式的 r.

Note that you only need triple quotes for multiline strings. What's important is the r for the pattern.

或者,rstrip 用于删除尾随空格:

Alternatively, rstrip is used to remove trailing whitespace:

str = str.rstrip()

这篇关于使用python删除尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆