10.7) Stripping Lines And Words Of Special Characters
When reading a file, the lines will all end in a \n special character, which means end of line. There’s a handy function which removes \n and other spaces or specific characters from strings.
To remove a leading \n from a line you just read from a file:
>>> "This is a line.\n".strip()
Remove punctuation around words: If you’ve split your line into words using the split command, you might also want to remove the punctuation around your words, such as tailing commas and full stops. For example:
>>> words="Hello, World!\n".split() >>> words ['Hello,', 'World!'] >>> words[0].strip(',.;:!?')
And if you want to strip all the words of potential punctuation, remember you can use a list comprehension:
>>> stripped_words=[word.strip(',.;:!?') for word in words]