[Tutor] re: [Totor] string iteration

Lloyd Hugh Allen lha2@columbia.edu
Sat, 10 Mar 2001 06:24:13 -0500


ewe2 wrote:
> given a string a = 'abcdefghijklmnop' and a string b = 'abc', how do i
> iterate b against a, so i get a string c = 'abcabcabcabcabca' the length of a?
> my brain is hurting from all the failed for loops :)

Here's my go, along with the thinking that went into it

>>> a = 'abcdefghijklmnopq'
>>> len(a)
17

#wanted to make sure that len(a) is not divisible by 3--if it were, it
would be easy to get a function that works today but fails to work
tomorrow

>>> b='abc'
>>> len(b)
3

#I'm relatively new to Python, and wanted to make sure that len(foo)
doesn't have off-by-one from the behavior that I would expect. It acts
as I expect.

>>> c=''

#initialize the target string--probably could have used a more
descriptive name

>>> for foo in range(len(a)):
	c=c+b[foo%len(b)]

#you weren't clear about how the for loops were failing. The thing that
kept throwing me off at first is that for has to iterate over a list,
not just up to a ceiling--range(x) returns a list that goes from 0 to
x-1, which is x units long. '%' is the (integer) modular division
operation (return the remainder of the division operation, which in this
case will be a number between 0 and 2).
	
>>> c
'abcabcabcabcabcab'

# it worked.

Because you didn't give your math and python background, and because I'm
good in math but new to Python, I overcommented (in large part for my
own benefit)--hope it only annoyed a few folks on the list.

-LHA