[Tutor] how to strip whitespaces from a string.
Anna Ravenscroft
revanna at mn.rr.com
Fri Oct 8 22:27:23 CEST 2004
Chad Crabtree wrote:
> kumar s wrote:
>
>
>>Thank you.
>>But I messed up my question.
>>s = " I am learning python "
>>f = s.strip()
>>f
>>'I am learning python'
>>
>>How can I get the ouput to:
>>
>>'Iamlearningpython'.
>>
>>
>>
>
> How about this
>
> s=" I am Learning Python "
> s="".join([x.strip() for x in s.split(' ')])
> print s
> IamLearningPython
That's close to what I would recommend.
I'd like to break this down a little bit for newbies, as you're doing
several (really good!) things at once here:
s.split() will split based on any character, word, punctuation or
whitespace - so, for example, if you have comma-separated values, you
could split at the comma. It's really handy to know.
The .join method is a little more confusing for newcomers sometimes.
It's a string method, but the method is on the *separator*, not on the
list of pieces being joined. If you use ''.join() with *no* whitespace,
it'll join all the pieces of a list back into a string with no
whitespace between. Like .split(), you can join with whatever string
characters, including whitespace, punctuation, whole words, whatever you
like.
The list of pieces to be joined has been created here with a list
comprehension [x.strip() for x in s.split(' ')]. This is an
exceptionally kewl piece of coding that became available in Python 2.x
You can pretty much turn *any* sequence into a list this way. The
syntax, again, is a little confusing for a lot of newbies: to me, it
seemed like I was telling it what to *do* to x before I told it what x I
wanted... It took a while to get used to. The syntax is:
[operation_if_any for item in list_of_items if optional_condition]
If list comprehensions blow your mind, try a simple for loop, which can
show you what the list comprehension is doing:
s = " I am learning Python "
mylist = []
for x in s.split(' '):
mylist.append[x]
If you print mylist, you'll see that the list contains all the pieces of
the string that were separated by white spaces (including some empty
strings where there were leading and trailing whitespaces). List
comprehensions can do this in one nice step without having to even
*name* the list, which is really kewl when you only want is a temporary
container anyway, like here.
Note that the x.strip is redundant here - when you used .split(' '), it
took off all the whitespace. So, what I would recommend is:
s = ''.join([x for x in s.split(' ')])
print s
IamlearningPython
HTH,
Anna
More information about the Tutor
mailing list