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

前端 未结 5 1503
感动是毒
感动是毒 2021-01-13 05:40

my output from a forloop is

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

print(string)

5
66
777

I use

5条回答
  •  不思量自难忘°
    2021-01-13 06:19

    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))
    

提交回复
热议问题