Strings for a newbie

Marc Boeren m.boeren at guidance.nl
Fri May 27 09:41:06 EDT 2005


Hi Malcolm,

> It's not the amout of code thats a probelm, it's following the
> logic and structure thats important.
> As I said Python.. UGH!

Do you find 

.. s = "This is a sentence of words"
.. a = s.split(' ')

less readable or logical than 

.. s = "This is a sentence of words"
.. For i = 1 to CountFields(s," ")
..     a.append NthField(s," ",i)
.. next



It seems you actual problem is more in this code you posted:

.. for x in range(len(l)):
..     h = string.split(l[x])

where l[x] does not evaluate to a string and thus it can't be split.
To find the value of l[x], just do 

.. for x in range(len(l)):
..     print l[x]
..     h = string.split(l[x])

and see what the print statement returns.
note that the code from Wolfram makes this a bit more readable:

.. for x in l:
..   print x
..   h = x.split()

Also note that you can play around with stuff like this in the
interactive interpreter, so you are not carrying around the whole of the
program you're writing. This makes experimenting with python a bit
easier as it's a quick way to check how things work. Whenever you see
code on this list that is prepended by >>> it means it is probably
copy/pasted from the interactive interpreter, so you know it actually
works (Johns example):

.. >>>s = "This is a sentence of words"
.. >>>a = s.split()
.. >>>a
.. 
.. ['This', 'is', 'a', 'sentence', 'of', 'words']

Have fun, Marc.




More information about the Python-list mailing list