Remove Space at end of String but keep new line symbol

心不动则不痛 提交于 2019-12-12 16:26:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!