4

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
Emmet B
  • 5,341
  • 6
  • 34
  • 47

3 Answers3

11

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'
poke
  • 369,085
  • 72
  • 557
  • 602
2

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.

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • 2
    You have redundant parenthesis: `','.join("a%d" % i for i in range(1,20))` – Dan D. Mar 30 '15 at 06:23
  • 1
    Unlike common belief, joining on a generator expression is *not* more efficient than joining on a list directly. See [this answer](http://stackoverflow.com/a/9061024/216074) for details. – poke Mar 30 '15 at 06:24
  • @DanD. they're not redundant, they're explicit -- if you were to need additional arguments to the outer function (`join`, in this case), you would need them. – jedwards Mar 30 '15 at 06:24
  • @poke, I could never argue with Raymond Hettinger -- will update accordingly. – jedwards Mar 30 '15 at 06:25
  • @jedwards There are no other possible arguments to `str.join`. – poke Mar 30 '15 at 06:26
  • 1
    @poke, I agree. But in the spirit of "explicit is better than implicit", I tend to leave them, to avoid future confusion. If the same generator were applied to say, `max(..., key=...)`, it would be an odd use indeed, but you would need the parens. – jedwards Mar 30 '15 at 06:30
1

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)]
hNomad
  • 11
  • 3