How to strip all whitespace from string

Taking advantage of str.split’s behavior with no sep parameter: If you just want to remove spaces instead of all whitespace: Premature optimization Even though efficiency isn’t the primary goal—writing clear code is—here are some initial timings: Note the regex is cached, so it’s not as slow as you’d imagine. Compiling it beforehand helps some, but … Read more

Python strip with \n [duplicate]

You should be able to use line.strip(‘\n’) and line.strip(‘\t’). But these don’t modify the line variable…they just return the string with the \n and \t stripped. So you’ll have to do something like That should work for removing from the start and end. If you have \n and \t in the middle of the string, you need to do to replace the \n and \t with nothingness.

strip(char) on a string

You need to replace() in this use case, not strip() strip(): string.strip(s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the … Read more