my output from a forloop is
string = \"\"
for x in something:
#some operation
string = x += string
print(string)
5
66
777
I use
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
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
l = [5, 66, 777]
print('{0}, {1}, {2}'.format(*l))
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)