Reputation: 11
I have a function I wrote in python that simple makes a horizontal list of int. I modified the print statement so that the list would print with commas, but the function adds one after the last int.
Any ideas as how to get rid of it?
num = list(range(20))
def count(x):
for i in range(len(x)):
# i+1 add in order to remove beginning zero.
print(i+1,end=',')
count(num)
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
Upvotes: 1
Views: 1727
Reputation: 101
Rather than creating a function, an output sequence can be processed with the range command:
num = range(1,21,1)
print num
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Print without the braces:
num = range(1,21,1)
print str(num).strip('[]')
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
User chooses start and ending numbers somewhere earlier in the code:
start = 56
end = 69
num = range(start, end + 1)
print str(num).strip('[]')
Output is:
56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69
User supplies start and stop interactivly:
start = raw_input('Choose start')
end = raw_input('Choose end')
num = range(start, end + 1)
print str(num).strip('[]')
Upvotes: 0
Reputation: 69031
A better function name would be display
, and the function you want is str.join()
:
def display(list_data):
print(', '.join(list_data))
The thing to keep in mind is the pieces to join must be strings, so you may need to convert:
', '.join([str(i) for i in list_data])
Upvotes: 0
Reputation: 1420
Add each number to a string and then print the string minus the last character:
num = list(range(20))
def count(x):
s = ""
for i in range(len(x)):
# i+1 add in order to remove beginning zero.
s += str(i+1) + ","
print(s[:-1])
count(num)
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
Upvotes: 0
Reputation: 10877
Try this:
num = list(range(20))
l = []
def count(x):
for i in range(len(x)):
l.append(i+1)
count(num)
print(l)
Outpout:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
You can also modify it to this:
def count(x):
for i in range(len(x)):
# i+1 add in order to remove beginning zero.
if i < len(x)-1:
print(i+1, end=',')
else:
print(i+1)
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
Upvotes: 2
Reputation: 2134
Try this:
num = list(range(20))
def count(x):
for i in range(len(x)-1):
print(i+1,end=',')
print(len(x))
count(num)
Upvotes: 0