[Tutor] function for removing all white spaces from a string

Bill Campbell bill at celestial.net
Mon Oct 1 22:47:55 CEST 2007


On Mon, Oct 01, 2007, Alan Gauld wrote:
>
>"Tim" <timmichelsen at gmx-topmail.de> wrote
>
>> after reading the responses to athread in 2004 [1] I am wondering 
>> why there is
>> no easy function in python to remove all white spaces from a string.
>>
>> " i am very fine "
>> to
>> "iamveryfine"
>
>You can use string.replace.
>
>>>> 'I am very fine'.replace(' ','')
>'Iamveryfine'
>>>>
>
>But you need to apply several times if you want more than simple 
>spaces removed.
>
>Or you can use regexs. (Or the translate function might work too, but 
>i haven't
>tried it for this)

import re
whitespace = re.compile(r'\s+')
cleanstring = whitespace.sub('', dirtystring)

Bill
--
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

Marijuana will be legal some day, because the many law students
who now smoke pot will someday become congressmen and legalize
it in order to protect themselves.
		-- Lenny Bruce


More information about the Tutor mailing list