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)
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.
Note that you only need triple quotes for multiline strings. What's important is the r
for the pattern.
Alternatively, rstrip
is used to remove trailing whitespace:
str = str.rstrip()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…