Jason Howard
Jason Howard

Reputation: 1586

Preventing removal of linebreaks

I have a function that replaces offensive words with a star, but in running text through this, it strips out linebreaks. Any thoughts on how to prevent this?

def replace_words(text, exclude_list):
    words = text.split()
    for i in range(len(words)):
        if words[i].lower() in exclude_list:
            
            words[i] = "*"
    return ' '.join(words)

Upvotes: 0

Views: 42

Answers (3)

Jason Howard
Jason Howard

Reputation: 1586

credit to mkrieger1

def replace_words(text, exclude_list):

    paragraphs = text.split('\n')

    new_paragraph = ""

    for p in paragraphs:

        words = p.split()
        for i in range(len(words)):
            if words[i].lower() in exclude_list:
                

                words[i] = "*"
        new_p = ' '.join(words)

        new_paragraph = new_paragraph + "\n" + new_p #add line break

    return new_paragraph

Upvotes: 1

Jason
Jason

Reputation: 92

You can use \n to create a new line or .split()

Upvotes: 0

mkrieger1
mkrieger1

Reputation: 23264

Don't use .split() with no argument on the entire input string, it removes line breaks and you lose the information where you have to put them in the result string.

You could first split the input into lines and then process each line separately in the same way as you now process the whole input.

Upvotes: 2

Related Questions