How to remove last comma from print(string, end=“, ”)

Question:

my output from a forloop is

string = ""
for x in something:
   #some operation
   string =  x += string 

print(string)

5
66
777

I use the below code to have them on the same line

print(string, end=", ")

and then I get

5, 66, 777,

I want the final result to be

 5, 66, 777

How do I change the code print(string, end=", ") so that there is no , at the end

The above string is user input generated it can me just 1 or 2,3, 45, 98798, 45 etc

So far I have tried

print(string[:-1], end=", ")                   #result = , 6, 77, 
print((string, end=", ")[:-1])                 #SyntaxError: invalid syntax  
print((string, end=", ").replace(", $", ""))   #SyntaxError: invalid syntax  
print(", ".join([str(x) for x in string]))     # way off result 5
                                                                6, 6
                                                                    7, 7, 7
    print(string, end=", "[:-1])                  #result 5,66,777,(I thought this will work but no change to result)
   print(*string, sep=', ')                          #result 5
                                                             6, 6
                                                             7, 7, 7 

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

user input
twenty five, four, nine 

gets

25, 4, 9, #(that stupid comma in the end)
Asked By: Samir Tendulkar

||

Answers:

You could build a list of strings in your for loop and print afterword using join:

strings = []

for ...:
   # some work to generate string
   strings.append(sting)

print(', '.join(strings))

alternatively, if your something has a well-defined length (i.e you can len(something)), you can select the string terminator differently in the end case:

for i, x in enumerate(something):
   #some operation to generate string

   if i < len(something) - 1:
      print(string, end=', ')
   else:
      print(string)

UPDATE based on real example code:

Taking this piece of your code:

value = input("")
string = ""
for unit_value in value.split(", "):
    if unit_value.split(' ', 1)[0] == "negative":
        neg_value = unit_value.split(' ', 1)[1]
        string = "-" + str(challenge1(neg_value.lower()))
    else:
        string = str(challenge1(unit_value.lower()))

    print(string, end=", ")

and following the first suggestion above, I get:

value = input("")
string = ""
strings = []
for unit_value in value.split(", "):
    if unit_value.split(' ', 1)[0] == "negative":
        neg_value = unit_value.split(' ', 1)[1]
        string = "-" + str(challenge1(neg_value.lower()))
    else:
        string = str(challenge1(unit_value.lower()))

    strings.append(string)

print(', '.join(strings))
Answered By: Joshua R.

In case your for loop is doing also something else than printing, then you can maintain your current structure with this approach.

 strings = ['5', '66', '777']

 for i in range(len(strings)-1):
      # some operation

      print(strings[i], end=', ')

 # some operation (last time)
 print(strings[-1])

5, 66, 777

Answered By: Ville Laitila

If you can first construct a list of strings, you can then use sequence unpacking within print and use sep instead of end:

strings = ['5', '66', '777']

print(*strings, sep=', ')

5, 66, 777
Answered By: jpp
list_name = [5, 10, 15, 20]
new_list = []
[new_list.append(f'({i}*{i+5})') for i in list_name] 
print(*new_list,sep="+") 

Output: (5*10)+(10*15)+(15*20)+(20*25)
Answered By: danish
for i in range(1,10):
    print(i, end="+")
    
print("10")

Output:

1+2+3+4+5+6+7+8+9+10

in the end no + sign.

Answered By: Vishal Kadam

see I have solved this to print 1 to 5
Previously:

i = 1
while i<=5:
    print(i, end=",")
    i=i+1

Output:==> 1,2,3,4,5,

Now

lst=[]
i=1
while i<=5:
    lst.append(str(i))
    i=i+1  
print(', '.join(lst))

Output:==> 1,2,3,4,5

Answered By: Rajshree

I can suggest you to use a if-condition inside a for-loop like below

x=['1','2','3','4','5']           #Driver List
for i in range(0,len(x),1):       #This loop iterates through the driver list
    if( i==len(x)-1 ):            #This checks whether i reached the last positon in iteration
        print(i)                  #If i is in the last position, just print the value of i
    else:
        print(i,end=" , ")        #If i is not in the last position, print the value of i followed by a comma

The output for this code is:

0 , 1 , 2 , 3 , 4               #Notice that no comma is printed in the last position
Answered By: DrinkandDerive

If text formatting is a concern, the simplest approach is to remove the last comma as shown in this example:

letters = ["a", "b", "c", "d", "e", "f"] 

for i in letters: 
    print(f"{i}".upper(), end=", ") # some text formatting applied
    
print("bb ")  # This removes the last comma.

Otherwise,

print (*letters, sep=", ") 

works pretty well.

Answered By: pibe regio
for i in range(10):
    if(i==9):
        print(i)
    else:
        print(str(i),end=",")

output : 0,1,2,3,4,5,6,7,8,9

Answered By: Mostofa On the way
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.