Strings for a newbie

James Hofmann jhofmann at ucsc.edu
Sat May 28 22:11:49 EDT 2005


Malcolm Wooden <mwooden <at> dtptypes.com> writes:

> 
> I'm trying to get my head around Python but seem to be failing miserably. I 
> use RealBasic on a Mac and find it an absolute dream! But Python....UGH!
> 
> I want to put a sentence of words into an array, eg "This is a sentence of 
> words"
> 
> In RB it would be simple:
> 
> Dim s as string
> Dim a(-1) as string
> Dim i as integer
> 
> s = "This is a sentence of words"
> For i = 1 to CountFields(s," ")
>   a.append NthField(s," ",i)
> next
> 
> That's it an array a() containing the words of the sentence.
> 
> Now can I see how this is done in Python? - nope!
> 
> UGH!
> 
> Malcolm
> (a disillusioned Python newbie) 
> 

This is the "verbose" version.

s = "This is a sentence of words"
nextword = ""
words = []
for character in s:
    if character==" ":
        words.append(nextword)
        nextword = ""
    else:
        nextword+=character # string types use += instead of append
words.append(nextword) # include the last word
print words

The main sticking point for you was probably understanding the way Python lets
you loop through sequence types. In general, sequences(list, string, etc.) can
be iterated either by an explicit function call, item = sequence.next(), or more
commonly with "for item in sequence:" which will make Python go through every
item it sees inside the sequence.

This turns out to be more convenient than keeping a seperate counter in the vast
majority of cases, because it cuts straight to the business of manipulating each
item, rather than tracking where it is.

Now a "slim" version:

s = "This is a sentence of words"
print s.split()
 
But there's no learning from that one, it's just an easy library call.




More information about the Python-list mailing list