Pythonic way to trim and keep leading and trailing whitespace

Tim Chase python.list at tim.thechases.com
Tue Mar 23 19:38:10 EDT 2010


python at bdurham.com wrote:
> I'm looking for a pythonic way to trim and keep leading
> whitespace in a string.
> 
> Use case: I have a bunch of text strings with various amounts of
> leading and trailing whitespace (spaces and tabs). I want to grab
> the leading and trailing whitespace, save it, surround the
> remaining text with html tags, and then add back the leading and
> trailing whitespace.
> 
> The only solution I can think of is regex, and that makes me
> think of the 2 proverbial problems that come with that :)

Just in case you're okay with a regexp solution, you can use

   >>> s = "\t\tabc def   "
   >>> import re
   >>> r = re.compile(r'^(\s*)(.*?)(\s*)$')
   >>> m = re.match(s)
   >>> m.groups()
   ('\t\t', 'abc def', '   ')
   >>> leading, text, trailing = m.groups()

While Emile's solution works nicely for your particular use-case, 
in the event you need to discern between leading/trailing 
whitespace, the above makes it pretty easy.

-tkc






More information about the Python-list mailing list