I'm using a for loop and it concatenates a string as such:
list1 = ["Hi","There"]
final = ""
for item in list1:
final += item + "\n"
It prints out:
Hi
There
#extra space here instead of comment
Now I know the solution where you do for i in range(len(list1)) and then you use "i" in an if statement to check if it's the last line, but this is problematic for me in my bigger case (which is not shown here).
What are some other alternatives to getting rid of the extra blankline? Like a trim or regex? I don't know, just suggestions.
You can use join
to insert newlines only between each element of the list:
final = '\n'.join(list1)
Or you can use strip
on the output of your loop:
list1 = ["Hi","There"]
final = ""
for item in list1:
final += item + "\n"
final = final.strip()