0

I seem to be stumped on this one. Unfortunately, I'm not even sure how to explain what I want. For n iterations in a loop, I want to print a letter n times. Here's some starter code...

n = 1
max = 3

letters = string.lowecase
letters.split

while n <= max:
    for letter in letters:
        print letter #n times
    n = n + 1

I would like to end up with:

a b ... z aa ... zz aaa ... zzz

ktflghm
  • 169
  • 1
  • 3
  • 9
  • The question is already answered, so just a note: the pythonic way to iterate over a range is `for n in xrange(max):...`, then you don't need the last line `n = n + 1`. – bereal Apr 25 '12 at 02:58
  • 1
    This is covered _very well_ by the [standard Python tutorial](http://docs.python.org/tutorial/introduction.html#strings). – jogojapan Apr 25 '12 at 02:58
  • Ah, I understand xrange() now. I was lacking the vocabulary to figure out what I needed from the standard python tutorial. – ktflghm Apr 25 '12 at 03:02

6 Answers6

4

Strings can be multiplied.

>>> 'foo' * 4
'foofoofoofoo'
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4
for i in range(1, 10):
    for j in "abcdefghijklmnopqrstuvwxyz":
        print j * i
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
2
>>> import string
>>> letters = string.ascii_lowercase

>>> print("".join( x*n for n in range(1,4) for x in letters  ))

abcdefghijklmnopqrstuvwxyzaabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzzaaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

Use another loop:

# Prints the letters
for letter in letters:
        print letter

# Prints each letter 3 times:
for letter in letters:
    for i in xrange(3):
        print letter
Brendan Long
  • 53,280
  • 21
  • 146
  • 188
0
n = 1
max = 3

letters = string.lowecase
letters.split

while n <= max:
    for letter in letters:
        print letter * n
    n = n + 1

multiply works with strings

mkoryak
  • 57,086
  • 61
  • 201
  • 257
0

Other way of doing

(lambda s: ''.join([x*n for n in xrange(4) for x in s]))(letters)

Mirage
  • 30,868
  • 62
  • 166
  • 261