How do I trim whitespace from a string?

To remove all whitespace surrounding a string, use .strip(). Examples: >>> ‘ Hello ‘.strip() ‘Hello’ >>> ‘ Hello’.strip() ‘Hello’ >>> ‘Bob has a cat’.strip() ‘Bob has a cat’ >>> ‘ Hello ‘.strip() # ALL consecutive spaces at both ends removed ‘Hello’ Note that str.strip() removes all whitespace characters, including tabs and newlines. To remove only … Read more

How do I trim whitespace?

For whitespace on both sides, use str.strip: s = ” \t a string example\t ” s = s.strip() For whitespace on the right side, use str.rstrip: s = s.rstrip() For whitespace on the left side, use str.lstrip: s = s.lstrip() You can provide an argument to strip arbitrary characters to any of these functions, like … Read more

Remove all whitespace in a string

If you want to remove leading and ending spaces, use str.strip(): >>> ” hello apple “.strip() ‘hello apple’ If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ‘ ‘ U+0020 but not any other whitespace): >>> ” hello apple “.replace(” “, “”) ‘helloapple’ If you … Read more

Trim string in JavaScript?

All browsers since IE9+ have trim() method for strings: ” \n test \n “.trim(); // returns “test” here For those browsers who does not support trim(), you can use this polyfill from MDN: if (!String.prototype.trim) { (function() { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return … Read more