Read file without displaying space

Asked

Viewed 79 times

0

Guys, I’d like to know how to print a txt file without displaying line breaks and spaces.

For example, the text in the.txt file is this:

The rat chewed his clothes
Of the King of Rome

I’d like to print it so:

Oratoroeuaroupadoreideroma

Could someone give me a hand? VLW

2 answers

3


To remove all special characters, can use the isalnum function():

frase = "O rato roeu a roupa\n Do rei de Roma"
#Remove todos os caracteres especiais
frase = ''.join(e for e in frase if e.isalnum())
#Coloca tudo em minúsculo
frase = frase.lower()
#Coloca primeira letra maiúscula
frase = frase.capitalize()

print(frase)
  • 1

    Thank you Breno, it worked perfectly here

2

You can also do what you want with a regular expression. It may be a little exaggerated for the example you have, but it’s always good to know more ways to get to the end result.

All you need to do is search with the regular expression \s, searching for any white space, i.e., space, enter, tab, and then replace each of these found characters with an empty string:

import re
frase = "O rato roeu a roupa\n Do rei de Roma"
nova_frase = re.sub(r"\s", "", frase) # procura por \s e substitui por ""
print(nova_frase) # 'OratoroeuaroupaDoreideRoma'

Check it out at Ideone

Browser other questions tagged

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