Text indentation challenge

Viewed 62

How do i write a function that prints a text with 2 new lines after each of these characters: ".", "?" and ":"

** I am not allowed to use any modules

** There should be no space at the beginning or at the end of each printed line

This is the main function:

text_indentation = __import__('5-text_indentation').text_indentation

text_indentation("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Quonam modo? Utrum igitur tibi litteram videor an totas paginas commovere? \
Non autem hoc: igitur ne illud quidem. Fortasse id optimum, sed ubi illud: \
Plus semper voluptatis? Teneo, inquit, finem illi videri nihil dolere. \
Transfer idem ad modestiam vel temperantiam, quae est moderatio cupiditatum \
rationi oboediens. Si id dicis, vicimus. Inde sermone vario sex illa a Dipylo \
stadia confecimus. Sin aliud quid voles, postea. Quae animi affectio suum \
cuique tribuens atque hanc, quam dico. Utinam quidem dicerent alium alio \
beatiorem! Iam ruinas videres""")

My expected result is:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Quonam modo?

Utrum igitur tibi litteram videor an totas paginas commovere?

Non autem hoc:

igitur ne illud quidem.

Fortasse id optimum, sed ubi illud:

Plus semper voluptatis?

Teneo, inquit, finem illi videri nihil dolere.

and so on...

ive written this:

def text_indentation(text):
    for i in text:
        if i == "." or i == "?" or i == ":" or i == ",":
            print(i, end="\n")
            print()
        else:
            print(i, end="")

but it prints the texts with spaces at the beginning of each line

3 Answers

Maybe I'm missing something, but it seems like a few substitutions would do the job.

def text_indentation(text):
    print(text.replace(". ", ".\n\n").replace("? ", "?\n\n").replace(": ", ":\n\n"))

You could just check the letter before the space you are printing:

test = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Quonam modo? Utrum igitur tibi litteram videor an totas paginas commovere? \
Non autem hoc: igitur ne illud quidem. Fortasse id optimum, sed ubi illud: \
Plus semper voluptatis? Teneo, inquit, finem illi videri nihil dolere. \
Transfer idem ad modestiam vel temperantiam, quae est moderatio cupiditatum \
rationi oboediens. Si id dicis, vicimus. Inde sermone vario sex illa a Dipylo \
stadia confecimus. Sin aliud quid voles, postea. Quae animi affectio suum \
cuique tribuens atque hanc, quam dico. Utinam quidem dicerent alium alio \
beatiorem! Iam ruinas videres"""

def text_indentation(text):
    special_chars = [".", ":", "?", "!"]
    for idx, i in enumerate(text):
        if i in special_chars:
            print(i, end="\n")
            print()
        elif i == " ":
            if text[idx-1] in special_chars:
                continue
            else:
                print(i, end="")
        else:
            print(i, end="")

text_indentation(test)

There also is a minor error in your code: You don't seem to want a line break after a comma, but according to your code you do insert one. Another option would be to set a boolean flag to skip the next letter after .?!:.

Edit: The latter approach i mentioned looks like this:

def text_indentation(text):
    skip_next = False
    for idx, i in enumerate(text):
        if skip_next:
            skip_next = False
            continue
        if i in [".", ":", "?", "!"]:
            print(i, end="\n")
            print()
            skip_next = True
        else:
            print(i, end="")

Solution number 2 is more efficient.

Edit 2: You probably want to consider "!" as well.

I would write a function like so, what it essentially does is checks if the character in the text corresponds to a ., ? or a : and if so it truncates the text upto the index where the character is found, joins it with two newline characters ( \n ) and adds the rest of the text. You can use the <String>#strip() method to remove leading or trailing spaces and further check for spaces in newlines.

def format_text(text):
    # Split the text with 2 new lines after each of these characters: ".", "?" and ":"

    for i in range(len(text)): # Loop through the text 
        if text[i] in ".?:":
            text = text[:i+1] + "\n\n" + text[i+1:] # Add 2 new lines after each of these characters: ".", "?" and ":"
    # Remove the extra new lines at the beginning and at the end of the text
    text = text.strip()
    # make sure there are no spaces at the beginning or at the end of each printed line
    text = text.replace(" \n", "\n") # Remove the spaces at the beginning of each printed line
    text = text.replace("\n ", "\n") # Remove the spaces at the end of each printed line
    return text
Related