F
F
Fak32011-09-23 20:16:37
Python
Fak3, 2011-09-23 20:16:37

Python: Remove line breaks and extra spaces from a string?

Hello. Plz tell me how to solve the problem with minimal invention of bicycles. It is necessary to clear the line from hyphens (replace with spaces) and remove extra spaces and empty lines.
Now it's done like this:
' '.join(filter(None, map(unicode.strip, input_string.splitlines())))
Is there a more standard way?
Attempts to use the textwrap lib only lead to code bloat... Maybe I don't know how to cook it?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
U
un1t, 2011-09-23
@Fak3

Regular: In this example, we remove spaces at the beginning and end of the line and line break characters. Edit to suit your needs.
import re
mystr = " balabla\n zzz "
re.sub("^\s+|\n|\r|\s+$", '', mystr)

B
burdakovd, 2011-09-27
@burdakovd

' '.join(s.split())
won't fit?

A
Anatoly, 2011-09-23
@taliban

Regular \s+ is a great way =)

D
dikkini, 2013-01-21
@dikkini

__author__ = '[email protected]'

from itertools import groupby

def lines_filter(iterable):
    """
   input:
       any iterable
   output:
       generator or list
   """
    wait_chr = False
    is_begin = True
    #========================================================================================================
    # You can delete "groupby" and the result will not change, but will increase the length of the input list.
    #========================================================================================================
    for item, i in groupby(iterable):
        if item:
            is_begin = False
            if wait_chr:
                wait_chr = False
                yield ''
            yield item
        elif not is_begin and not wait_chr:
            wait_chr = True

if __name__ == '__main__':
    list1 =['','','','i','hgf', '','','','9876','','','7','','9','','',''] # Input list
    print [i for i in lines_filter(list1)] # Output to the list

H
Howling, 2020-10-23
@Howling

string.rstrip()
or
string = string.replace("\n","")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question