like a "for loop" for a string

Paul Boddie paul at boddie.org.uk
Sun Aug 17 22:20:45 CEST 2008


On 17 Aug, 20:22, Alexnb <alexnbr... at gmail.com> wrote:
> But I am wondering is there a way to something like this:
>
> funString = "string string string non-string non-string string"
> and
> for "string" in funString:
>       print something
>
> I know you can't do that; but, is there a way do do something similar that
> gets the same result?

Perhaps this...

  for s in funString.split():
      if s == "string":
          print something

Assuming that you want to iterate over the separate words in funString
(for which you need to use the split method on funString), and that
you only want to print something when the word being considered is
"string".

To understand why this may (or may not) be what you want, try and
articulate what needs to happen. You appear to want to treat funString
like the list of numbers, and it could be that you consider the
boundaries between the "elements" in funString to be spaces (although
you don't say). So, first we need to get a list which meets your
requirements:

  funString.split() # ["string", "string", "string", "non-
string", ...]

Then, you want to visit the elements in this list, perhaps - that's
where the "for" loop comes in. However, you use "string" as the loop
variable which isn't going to work (as you may already have
discovered). So let's use a variable instead:

  for s in funString.split():
      print s

This will print all the elements in that list. It appears that you
only want to consider "string", however, so that means that you need
to test the value of s and to only do something if s is equal to
"string" - that's where the "if" statement comes in.

When you have data which doesn't immediately fit into an existing
piece of code, don't be afraid to experiment at the Python prompt and
to try and turn your data into something the existing code can use.
And don't expect magic: if your first instinct produces a syntax error
('for "string" in funString') consider what you are trying to express
and then try and find language constructs to express it.

Paul



More information about the Python-list mailing list