Answer the question
In order to leave comments, you need to log in
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
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)
__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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question