Python how to remove last comma from print(string, end=“, ”)
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))
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