我要打印1000-3000范围内所有偶数的整数,然后将它们打印在一行中,每行之间用逗号分隔。到目前为止,这是我的代码:
for i in range (1000,3001):
s = str(i)
if i % 2 == 0:
print (i)
如果我尝试添加split()函数,则会发生此错误: 'int'对象没有属性'split'
我该怎么做?
答案 0 :(得分:2)
很简单:
print(','.join([str(i) for i in range(1000, 3001, 2)]))
或者:
print(*range(1000, 3001, 2), sep=',')
您无需检查偶数,因为您只需打印第二个以偶数开头的数字即可。
答案 1 :(得分:0)
对此的答案很简单,如下所示:
out = [str(i) for i in range(1000, 3001) if i % 2 == 0]
print(",".join(out))
输出为:
1000, 1002, ..., 3000
答案 2 :(得分:-1)
尝试一下,效果很好:
even_number_list=[] # taking an empty list to store even numbers
for i in range(1000,3001):
if(i%2==0):
even_number_list.append(i) # appending even numbers in our list
print(*even_number_list,sep=',') # unpacking list with values seperated by comma