Python按长度分割字符串且不截断单词的实现方案
Python实现单词不截断的字符串换行(每行≤120字符)
其实Python内置的textwrap模块就是专门解决这类需求的——自动在单词边界换行,保证每行长度不超指定值,还不会截断单词。
内置方案代码示例
import textwrap # 你的示例字符串 sample_str = "Here the line that have to be under 120 chars and cut at the point in the string where the last word is under 120 chars because this part have to be in the second line and it also needs to be seperated such as the string part before and this has to be in the third line with the end of the string" # 调用wrap方法,指定每行最大长度120 wrapped_lines = textwrap.wrap(sample_str, width=120) # 打印结果,每行单独输出 for line in wrapped_lines: print(line)
运行这段代码得到的结果和你期望的完全一致:
Here the line that have to be under 120 chars and cut at the point in the string where the last word is under 120 chars
because this part have to be in the second line and it also needs to be seperated such as the string part before and
this has to be in the third line with the end of the string
textwrap.wrap()默认会在单词之间的空格处换行,不会拆分单词,刚好匹配你的要求,之前没搞定可能是没正确使用这个方法。
手动实现逻辑(了解底层原理用)
要是你想自己写逻辑实现,思路也很清晰:
- 把字符串按空格拆成单词列表
- 维护当前正在构建的行,逐个添加单词,每次检查加完后的长度是否超过120
- 如果超过,就把当前行存入结果,用这个单词开启新行
- 最后把剩余的行存入结果
代码示例:
def wrap_string(s, max_width=120): words = s.split() lines = [] current_line = [] current_length = 0 for word in words: # 计算添加当前单词后的长度(需考虑空格) next_length = current_length + len(word) + (1 if current_line else 0) if next_length <= max_width: current_line.append(word) current_length = next_length else: # 当前行已满,存入结果 lines.append(' '.join(current_line)) current_line = [word] current_length = len(word) # 加入最后一行 if current_line: lines.append(' '.join(current_line)) return lines # 测试 wrapped = wrap_string(sample_str) for line in wrapped: print(line)
这个手动实现的逻辑也能达到同样的效果,适合你理解底层运行原理。
内容的提问来源于stack exchange,提问作者Ano Nymous
相关产品推荐
相关产品推荐

