Home > Enterprise >  Python - How to change final comma to a peroid after a list sentence and insert "and" as w
Python - How to change final comma to a peroid after a list sentence and insert "and" as w

Time:02-16

How can I edit this code to make it output something like "The prime number(s) in your range are: 11, 13, 17, 19, 23, and 29." if the boundaries are 10 and 30?

lower = int(input("Input lower bound"))
upper = int(input("Input upper bound"))
print("The prime number(s) in your range are:", end = " ")
for num in range(lower, upper 1):
  if(num>1):
    for i in range(2,num):
      if(num%i)==0:
        break
    else:
      print(num, end = ", ")

CodePudding user response:

Store them in a list and print them at the end , use sep argument to mention separation and end to mention the end.

lower = int(input("Input lower bound"))
upper = int(input("Input upper bound"))
print("The prime number(s) in your range are:", end = " ")
primenums = []
for num in range(lower, upper 1):
  if(num>1):
    for i in range(2,num):
      if(num%i)==0:
        break
    else:
      primenums.append(num)
if len(primenums) > 2:
  print(*primenums[:-1] ,sep = ", ",end=" and ")
  print(prime[-1])
else:
  # if len(primenums) is 1 sep will be ignonred
  print(*primenums,sep=" and ")

CodePudding user response:

Store your prime numbers in a list.

primes = []
for num in range(lower, upper 1):
  if(num>1):
    for i in range(2,num):
      if(num%i)==0:
        break
    else:
      primes.append(num)

Then, format it into a string before printing:

if len(primes) <= 2:
    msg = " and ".join(str(p) for p in primes)
else:
    msg = f"{', '.join(str(p) for p in primes[:-1])}, and {primes[-1]}"

print(f"The prime number(s) in your range are: {msg}")

", ".join(...) joins all elements in the iterator that is passed to it with the string ", ". The iterator is str(p) for p in primes[:-1]. This iterator converts all elements of primes except the last one to a string to be joined with ", ". The f"..." construct is called an f-string and is my preferred way of string interpolation in python.

CodePudding user response:

You could do something like this:

lower = int(input("Input lower bound: "))
upper = int(input("Input upper bound: "))

prime_numbers = list()
for num in range(lower, upper 1):
    if num > 1:
        for i in range(2, num):
            if num % i == 0:
                break
        else:
            prime_numbers.append(str(num))

print("The prime number(s) in your range are:", ", ".join(prime_numbers[:-1]), "and", prime_numbers[-1]   '.')

# With f-string
print(f"The prime number(s) in your range are: {', '.join(prime_numbers[:-1])} and {prime_numbers[-1]}.")

This would output:

The prime number(s) in your range are: 11, 13, 17, 19, 23 and 29.
The prime number(s) in your range are: 11, 13, 17, 19, 23 and 29.

Which keeps the and and .

  • Related