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

前端 未结 5 1483
感动是毒
感动是毒 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:13

    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

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2021-01-13 06:19

    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
    
    0 讨论(0)
  • 2021-01-13 06:27
    l = [5, 66, 777]
    print('{0}, {1}, {2}'.format(*l))
    
    0 讨论(0)
  • 2021-01-13 06:27

    list_1 = [5, 10, 15, 20]

    new_list = []
    [ new_list.append(f'({i}*{i+5})') for i in list_1 ] 
    print(*new_list,sep="+") 
    

    Output

    (5*10)+(10*15)+(15*20)+(20*25)
    
    0 讨论(0)
提交回复
热议问题