Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 668
Emmet B Avatar asked Dec 12 '22 00:12

Emmet B


1 Answers

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'
like image 96
poke Avatar answered Mar 04 '23 16:03

poke