Remove Space at end of String but keep new line symbol
Asked Answered
M

4

6

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?

Mckinzie answered 17/3, 2015 at 23:12 Comment(7)
Just to clarify, you're talking about strings like 'my test string', 'my test string ', and 'my test string \n, right? And you want to turn them into either 'my test string' or 'my test string\n'?Muddle
@Muddle I want to 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?Mckinzie
Okay; my answer should take care of that.Muddle
@Muddle There are a few problems. Strings might have only one character in them, so doing something like string[-2] would be out of bounds.Mckinzie
What if that one character is a space?Muddle
did you want to replace the space before last newline character with empty string?Page
So you want strings that end with two spaces to end with one space after this script runs?Petroleum
M
3
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'
Muddle answered 17/3, 2015 at 23:25 Comment(8)
str[-2] might be out of bounds though. I'm looking at a are variety of strings. Some of them may even be something like: "I\n"Mckinzie
This is really close. The string may also be something like: "I"Mckinzie
How about if the string is ' ', a single space? if len(str) > 1 and str[-1] == ' ': rather than if str[-1] == ' ': results in returning the single space. If you prefer that it turn ' ' into the empty string, use the latter.Muddle
Please don't use str... when I see it - all I can think is the builtin str... call it text or something - shadowing a built-in name is never good practice :(Haplology
Funny story: I was consciously attempting to avoid using string, and blundered right into str.Muddle
@Muddle been there done that... at least string is slightly better - as it's more likely someone wants to use str than the string module... but six of one, half dozen of the other etc...Haplology
Well, I'm sure that my_str is available - after all, I clearly scrawled "MINE!" on it.Muddle
@ninja_power: this code was for the original, unedited question that specified the end of the string. To handle ' \n' appearing anywhere in the string, use my_str.replace(' \n', '\n') as per Malonge's answer.Muddle
P
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'
Pignut answered 17/3, 2015 at 23:44 Comment(2)
What if ' \n' occurs somewhere other than the end of the string?Muddle
Interesting point, although I don't see how this opposes the specifications of the question. Wouldn't it still achieve the desired goal?Pignut
P
0

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)
Petroleum answered 23/7, 2017 at 11:48 Comment(0)
O
0

Input File:

filea.txt (With many spaces)

dragon
dragonballs

test.py

filea = open('filea.txt','r')
fileb = open('fileb.txt','a')
for line in filea:
for i in range(len(line)):
if ' \n' in line:
line = line.replace(' \n','\n')
fileb.write(line)

op:

fileb.txt

dragon
dragonballs

Ondometer answered 22/2, 2022 at 12:4 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Crossopterygian

© 2022 - 2024 — McMap. All rights reserved.