Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trim whitespace?

Is there a Python function that will trim whitespace (spaces and tabs) from a string?

Example: \t example string\texample string

like image 347
Chris Avatar asked Jul 26 '09 20:07

Chris


People also ask

What does it mean to trim whitespace?

Note that Trim Whitespace uses a fixed definition of whitespace that will remove all whitespace and non-printing characters from attribute values.

What is the best way to remove whitespace characters from the start or end?

To remove whitespace characters from the beginning or from the end of a string only, you use the trimStart() or trimEnd() method.

How do I trim a space in a string in python?

The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.


1 Answers

For whitespace on both sides use str.strip:

s = "  \t a string example\t  " s = s.strip() 

For whitespace on the right side use rstrip:

s = s.rstrip() 

For whitespace on the left side lstrip:

s = s.lstrip() 

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r') 

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import re print(re.sub('[\s+]', '', s)) 

That should print out:

astringexample 
like image 123
James Thompson Avatar answered Oct 25 '22 22:10

James Thompson