Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Python list filled with the same string over and over and a number that increases based on a variable.

I'm trying to create a list that is populated by a reoccurring string and a number that marks which one in a row it is. The number that marks how many strings there will be is gotten from an int variable.

So something like this:

b = 5
a = range(2, b + 1)
c = []
c.append('Adi_' + str(a))

I was hoping this would create a list like this:

c = ['Adi_2', 'Adi_3', 'Adi_4', 'Adi_5']

Instead I get a list like this

c = ['Adi_[2, 3, 4, 5]']

So when I try to print it in new rows

for x in c:
    print"Welcome {0}".format(x)

The result of this is:

Welcome Adi_[2, 3, 4, 5]

The result I want is:

Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5

If anybody has Ideas I would appreciate it.

like image 445
Adilicious Avatar asked Sep 27 '12 12:09

Adilicious


1 Answers

You almost got it:

for i in a:
    c.append('Adi_' + str(i))

Your initial line was transforming the whole list a as a string.

Note that you could get rid of the loop with a list comprehension and some string formatting:

c = ['Adi_%s' % s for s in a] 

or

c = ['Adi_{0}'.format(s) for s in a] #Python >= 2.6
like image 109
Pierre GM Avatar answered Sep 20 '22 15:09

Pierre GM