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

3 Answers 3

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'
Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

You have redundant parenthesis: ','.join("a%d" % i for i in range(1,20))
Unlike common belief, joining on a generator expression is not more efficient than joining on a list directly. See this answer for details.
@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.
@poke, I could never argue with Raymond Hettinger -- will update accordingly.
@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.
|
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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.