Emmet B
Emmet B

Reputation: 5531

Python: Short way of creating a sequential list with a prefix

how can I generate a string (or Pandas series) like below:

a1,a2,a3,a4,...,a19

the following works, but I would like to know a shorter way

my_str = ""
for i in range(1, 20):
   comma = ',' if i!= 19 else ''
   my_str += "d" + str(i) + comma

Upvotes: 4

Views: 8074

Answers (3)

hNomad
hNomad

Reputation: 11

Adding onto what poke said (which I found to be the most helpful), but bringing it into 2022:

[f'a{i}' for i in range(1, 21)]

Upvotes: 1

jedwards
jedwards

Reputation: 30210

What about:

s = ','.join(["a%d" % i for i in range(1,20)])
print(s)

Output:

a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19

(This uses a generator expression, which is more efficient than joining over a list comprehension -- only slightly, with such a short list, however) This now uses a list comprehension! See comments for an interesting read about why list comprehensions are more appropriate than generator expressions for join.

Upvotes: 2

poke
poke

Reputation: 387587

You can just use a list comprehension to generate the individual elements (using string concatenation or str.format), and then join the resulting list on the separator string (the comma):

>>> ['a{}'.format(i) for i in range(1, 20)]
['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19']
>>> ','.join(['a{}'.format(i) for i in range(1, 20)])
'a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19'

Upvotes: 11

Related Questions