打印多个分隔符Python 3

时间:2018-09-11 23:30:40

标签: python-3.x

我正在尝试打印出用户输入的两个数字之间的所有质数。我可以打印出定界符,但在如何打印多个定界符方面却很挣扎,然后重复进行直到所有素数都已打印完为止。 例如,定界符是“冒号,感叹号,逗号”。寻找类似的东西:7:11!13,17:19!23

num_1 = int(input("Enter your first number: "));
num_2 = int(input("Enter your second number: "));
num_3 = 0

if num_2 > num_1:
     num_3 = num_1
     num_1 = num_2
     num_2 = num_3

for num in range(num_1, num_2 +1):
     if num > 1:
         for i in range(2,num):
             if (num%i) == 0:
                break
          else:
              print(num, sep="", end=","

2 个答案:

答案 0 :(得分:2)

num_1 = int(input("Enter your first number: "));
num_2 = int(input("Enter your second number: "));
num_3 = 0

if num_2 > num_1:
     num_3 = num_1
     num_1 = num_2
     num_2 = num_3

ite_list = [":","!",","]
outa = []
for num in range(num_1, num_2 +1):
     if num > 1:
         for i in range(2,num):
             if (num%i) == 0:
                break
          else:
              outa.append(str(num) + ite_list[len(outa)%3])
outa = "".join(outa)
print(outa)

那样吗?

答案 1 :(得分:1)

您可以使用itertools.cycle()

例如:

import itertools
my_delimiters = itertools.cycle(":!,.")

# rest of the code

print(num, end=next(my_delimiters))