如何按指定单词数添加换行且不拆分完整单词?
How to Add Newlines After a Specific Number of Words (Without Splitting Words)
Got it, I see the problem with your current code—it's splitting mid-word because you're counting characters instead of tracking whole words. Let's fix that by rewriting the logic to wrap the text after a set number of complete words instead.
Here's a straightforward solution:
First, we'll split the input into individual words, then group them into chunks of your desired word count, and finally join those chunks back into lines separated by newlines.
inp = "A very very long string from user input" words_per_line = 3 # Adjust this number to set how many words per line words = inp.split() # Group words into lines of the specified length lines = [] for i in range(0, len(words), words_per_line): line_words = words[i:i + words_per_line] lines.append(' '.join(line_words)) # Join all lines with newlines new_input = '\n'.join(lines) print(new_input)
What this does:
inp.split()breaks the input string into a list of words (using spaces as separators), so we never have to deal with partial words.- The
range(0, len(words), words_per_line)loop steps through the word list in chunks of your chosen size—each chunk becomes one line. ' '.join(line_words)turns each chunk back into a string of complete words, and'\n'.join(lines)combines all those lines into the final formatted text.
Example output (with words_per_line = 3):
A very very long string from user input
If you ever need to adjust the number of words per line, just change the value of words_per_line—no other code changes needed!
内容的提问来源于stack exchange,提问作者Thịnh Phạm
相关产品推荐
相关产品推荐

