Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ignore non-words and apply a string method to words

Having a variable with a large message, how to ignore exclamation marks and symbols while applying a string method to the words that are part of this message?
Example:

message = "THIS IS A MESSAGE!!, A TEXT *THAT HAS MANY-- WORDS- "

The above should become:

"this is a message a text that has many words"

I did it as shown below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ignore_stuff = message.replace('*',"").replace('--',"").replace(",","").replace("!","")
turned_to_lower = ignore_stuff.lower()
print(turned_to_lower)

which gives the wanted result:

this is a message a text that has many words 

Is there a better way that still does not use any external libraries and also does not use regular expressions?

>Solution :

You can use .isalnum() and .isspace()

message = "This is a sentence --- and this is great."
message = "".join(ch.lower() for ch in message if ch.isalnum() or ch.isspace())
message = " ".join(message.split())
print(message)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading