问题
How can I check if a Python string at any point has a single space before new line? And if it does, I have to remove that single space, but keep the new line symbol. Is this possible?
回答1:
def remspace(my_str):
if len(my_str) < 2: # returns ' ' unchanged
return my_str
if my_str[-1] == '\n':
if my_str[-2] == ' ':
return my_str[:-2] + '\n'
if my_str[-1] == ' ':
return my_str[:-1]
return my_str
Results:
>>> remspace('a b c')
'a b c'
>>> remspace('a b c ')
'a b c'
>>> remspace('a b c\n')
'a b c\n'
>>> remspace('a b c \n')
'a b c\n'
>>> remspace('')
''
>>> remspace('\n')
'\n'
>>> remspace(' \n')
'\n'
>>> remspace(' ')
' '
>>> remspace('I')
'I'
回答2:
How about just replacing the specific instance of ' \n' with '\n'?
s1 = 'This is a test \n'
s1.replace(' \n', '\n')
>>> 'This is a test\n'
s2 = 'There is no trailing space here\n'
s2.replace(' \n', '\n')
>>> 'There is no trailing space here\n'
回答3:
If you want to strip multiple spaces, you can use regex:
import re
def strip_trailing_space(my_string):
return re.sub(r' +(\n|\Z)', r'\1', my_string)
def strip_trailing_whitespace(my_string):
return re.sub(r'[ \t]+(\n|\Z)', r'\1', my_string)
来源:https://stackoverflow.com/questions/29111443/remove-space-at-end-of-string-but-keep-new-line-symbol