Wrap text to an approximate display width with textwrap.fill().
How It Works
textwrap.fill(text, width) folds words into a new string containing line breaks. It is useful for console output, but it does not measure rendered proportional-font width.
Step-by-Step Example
import textwrap
paragraph_text = 'A short paragraph can be wrapped for a terminal display.'
wrapped_text = textwrap.fill(paragraph_text, width=22)
print('\n' in wrapped_text)
print(wrapped_text.splitlines()[0])
Understanding the Example
- The expression "'A short paragraph can be wrapped for a terminal display.'" supplies the value stored as 'paragraph_text'. This value is then used or checked by the later statements.
- The expression 'textwrap.fill(paragraph_text, width=22)' supplies the value stored as 'wrapped_text'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
A short paragraph can
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Use textwrap.wrap() if you need a list of lines instead of one string.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Assuming width measures pixels or that filling text preserves all original whitespace.
- Display a long help message at 40 characters per line.
Key Takeaways
- Wrap text to an approximate display width with textwrap.fill().
- textwrap.fill(text, width) folds words into a new string containing line breaks.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.