Python中while循环收集结果值时拼接错误的问题排查
Hey there! Let's break down why your code is outputting separate lines instead of a single continuous string:
The Root Problem
You're resetting Blank_text to an empty string inside the while loop with this line:
Blank_text = ""
This means every time the loop runs, you throw away any text you've already concatenated and start fresh with just the current <colspec> tag. Then you print that single tag immediately, which is why you get each one on a new line.
The Fix
Move the initialization of Blank_text outside the loop, so it starts empty once and you build on it with each iteration. Then wait until the loop finishes to print the full concatenated string:
ColumnCount_int = 3 Blank_text = "" # Initialize once before the loop while ColumnCount_int > 0 : # Simplified string creation (removed unnecessary extra spaces) ColumnCount_text = f'<colspec colnum="{ColumnCount_int}" colname="{ColumnCount_int}">' Blank_text += ColumnCount_text # Add the new tag to the existing string ColumnCount_int -= 1 # Shorter way to decrement the counter print(Blank_text)
What This Does
Blank_textstarts empty and keeps growing with each<colspec>tag as the loop runs.- After the loop completes, you print the entire assembled string in one go, resulting in a single continuous line like this:
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">
Bonus: Clean Up the String Formatting
I used an f-string (f'') to make the string creation much cleaner and easier to read—no more messy string concatenation with + signs. This is the recommended way to format strings in Python 3.6+.
内容的提问来源于stack exchange,提问作者Cho

