diff --git a/Lib/test/test_textwrap.py b/Lib/test/test_textwrap.py index aca1f427656bb5..66e7a26774a0c9 100644 --- a/Lib/test/test_textwrap.py +++ b/Lib/test/test_textwrap.py @@ -388,6 +388,8 @@ def test_drop_whitespace_leading_whitespace(self): [" This is a sentence with leading whitespace."]) self.check_wrap(text, 30, [" This is a sentence with", "leading whitespace."]) + self.check_wrap(' ABCDEFG', 1, + [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G']) def test_drop_whitespace_whitespace_line(self): # Check that drop_whitespace skips the whole line if a non-leading diff --git a/Lib/textwrap.py b/Lib/textwrap.py index 41366fbf443a4f..ba1307f003bd8b 100644 --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -304,8 +304,12 @@ def _wrap_chunks(self, chunks): # If the last chunk on this line is all whitespace, drop it. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': - cur_len -= len(cur_line[-1]) - del cur_line[-1] + # If this is the first line keep it if a non-whitespace chunk follows + if not lines and len(cur_line) == 1 and chunks and chunks[-1].strip() != '': + pass + else: + cur_len -= len(cur_line[-1]) + del cur_line[-1] if cur_line: if (self.max_lines is None or diff --git a/Misc/NEWS.d/next/Library/2025-10-26-16-11-45.gh-issue-140627.BiEgy_.rst b/Misc/NEWS.d/next/Library/2025-10-26-16-11-45.gh-issue-140627.BiEgy_.rst new file mode 100644 index 00000000000000..1c03751cbeadd6 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-10-26-16-11-45.gh-issue-140627.BiEgy_.rst @@ -0,0 +1,2 @@ +Fix :func:`textwrap.wrap` to preserve a whitespace only line at the start of +a paragraph when non-whitespace text follows.