print text without translineation rule

Asked

Viewed 97 times

2

I need to print a text from a file on a single line without the line break traces.

def imprime_texto():
with open("texto.txt") as arquivo:
    linhas = arquivo.read().split("\n")
for linha in linhas:
    print(linha.strip(), end=" ")

Entree:

  Programar em python é mui-
  to simples é só praticar.

Correct exit : without the dash.

  Programar em python é muito simples é só praticar.

My exit is with the dash in mui-to and at the end comes out the None I don’t know where I’m going wrong in the code.

  Programar em python é mui- to simples é só praticar. None

1 answer

3


To remove the -

or remove it from the entrance

Programar em python é mui 
to simples é só praticar.

or it is possible to use the replace

for linha in linhas:
    linha = linha.replace("-", "")
    print(linha.strip(), end=" ")

Obs: use the replace can be bad as it will remove any input you have -, ex: prehistory will stay prehistory

Already to remove the white space that is getting after the -, just change your end for

print(linha.strip(), end="")

follows as the code:

def imprime_texto():
    with open("C:\\Shared\\teste.txt") as arquivo:
        linhas = arquivo.read().split("\n")
    for linha in linhas:
        linha = linha.replace("-", "")
        print(linha.strip(), end="")
imprime_texto()

Exit:

Programming in python is very simple just practice.

EDIT

As commented by Miguel there is another solution, which is much better and with less code than the above solution, would do all process in reading the file.

def imprime_texto():
    with open("C:\\caminho\\teste.txt") as arquivo:
        linhas = arquivo.read().replace("-\n", "").replace('\n', "")
        print(linhas)        
imprime_texto()

EDIT 2

We have another solution!!!

Now commented by Isac

"Another interesting solution to remove the - is to make strip("-") that also ensures that only catches those at the end of each line "

def imprime_texto():
    with open("C:\\caminho\\teste.txt") as arquivo:
        linhas = arquivo.read().split("\n")
    for linha in linhas:
        linha = linha.strip("-")
        print(linha.strip(), end="")
imprime_texto()
  • Obgado, I didn’t need to give the credit. I’m glad I helped +1

  • Thanks friends, it worked perfectly.

  • @Miguel merits always ;)

  • @Bruno don’t forget to mark as answered https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

  • 1

    Okay Barbetta can leave friend.

  • Another interesting solution to remove the - is to make strip("-") which also ensures that only catches those at the end of each line

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.