0

I got this code

for n in range(10,20):
 print(n, end='')
 print(', ', end='')

I get this:

10, 11, 12, 13, 14, 15, 16, 17, 18, 19,

How do I remove the last comma? Have been searching for like 30 minutes with no luck. Are there any easy command I can just put last in the code to remove the last character?

Edit:

Solution: There is different ways to solve this but the assignment was to add a code, not make a new one so this solution worked best for me.

for n in range(10,20):
 print(n, end='')
 if n >= 19:
    break
 print(', ', end='')

Machavity
  • 30,841
  • 27
  • 92
  • 100
ClearWhey
  • 3
  • 2
  • 1
    You can use `', '.join(...)` to comma-join a sequence of strings. So all you need is a sequence of strings. – khelwood Nov 24 '20 at 19:48
  • While the `join` method is the most pythonic way to solve this problem, think about how you might write a generic algorithm to solve the problem in any language. The most common way to avoid printing the final delimiter on a sequence of items is to maintain a count of items printed and compare that count to the length of the sequence/list. When your count equals the size of the list (depending on how you initialize the count and when you increment it) then you no longer print the delimiter (in this case the comma). – h0r53 Nov 24 '20 at 19:51

1 Answers1

3

You can create a list of items and then join them with ", ". Or use a generator as in

>>> print(", ".join(str(n) for n in  range(10, 20)))
10, 11, 12, 13, 14, 15, 16, 17, 18, 19
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    Or more functional: `print(', '.join(map(str, range(10, 20))))` – Matthias Nov 24 '20 at 19:52
  • @Matthias - True, but "functional" doesn't mean better. Guido doesn't like `map` and friends _"I think dropping filter() and map() is pretty uncontroversial; filter(P, S) is almost always written clearer as [x for x in S if P(x)], ..."_ ([The fate of reduce() in Python 3000](https://www.artima.com/weblogs/viewpost.jsp?thread=98196)). And I agree with that. Comprehensions and generators are the "pythonic" way to do it IMHO. – tdelaney Nov 24 '20 at 19:58