Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to wrap a text into paragraph with width w
Text wrapping is a common task when formatting output for display or printing. Python's textwrap module provides the fill() function to wrap text into paragraphs with a specified width.
Syntax
textwrap.fill(text, width=70, **kwargs)
Parameters
The fill() function accepts the following parameters:
text − The string to be wrapped
width − Maximum line width (default is 70)
break_long_words − Break words longer than width (default True)
break_on_hyphens − Break on hyphens (default True)
Basic Text Wrapping
Let's wrap a text string with width 9 ?
import textwrap
def wrap_text(text, width):
return textwrap.fill(text, width)
text = "The quick brown fox jumps over the lazy dog"
width = 9
result = wrap_text(text, width)
print(result)
The quick brown fox jumps over the lazy dog
Different Width Examples
Here's how the same text looks with different widths ?
import textwrap
text = "The quick brown fox jumps over the lazy dog"
# Different widths
widths = [15, 20, 30]
for w in widths:
print(f"Width {w}:")
print(textwrap.fill(text, w))
print("-" * w)
Width 15: The quick brown fox jumps over the lazy dog --------------- Width 20: The quick brown fox jumps over the lazy dog -------------------- Width 30: The quick brown fox jumps over the lazy dog ------------------------------
Advanced Options
Control word breaking and hyphen handling ?
import textwrap
text = "This is a super-long-hyphenated-word example"
# Default behavior
print("Default:")
print(textwrap.fill(text, 20))
print()
# Don't break on hyphens
print("break_on_hyphens=False:")
print(textwrap.fill(text, 20, break_on_hyphens=False))
print()
# Don't break long words
print("break_long_words=False:")
print(textwrap.fill(text, 20, break_long_words=False))
Default: This is a super-long- hyphenated-word example break_on_hyphens=False: This is a super-long- hyphenated-word example break_long_words=False: This is a super-long-hyphenated-word example
Comparison
| Method | Use Case | Preserves Words |
|---|---|---|
textwrap.fill() |
Simple paragraph formatting | Yes |
textwrap.wrap() |
Returns list of lines | Yes |
| Manual splitting | Custom logic needed | Depends on implementation |
Conclusion
Use textwrap.fill() to wrap text into paragraphs with specified width. The function intelligently breaks at word boundaries and provides options for handling long words and hyphens.
