textwrap मॉड्यूल टेक्स्ट को निर्दिष्ट चौड़ाई में रैप/फिल करने के लिए TextWrapper क्लास और सुविधा फ़ंक्शन्स प्रदान करता है।
मुख्य फ़ंक्शन्स
wrap(text, width=70)
पैराग्राफ को लाइन्स की लिस्ट में रैप करता है (अंतिम न्यूलाइन के बिना)।
import textwrap
sample_text = """The textwrap module provides some convenience functions,
as well as TextWrapper class that does all the work."""
for line in textwrap.wrap(sample_text, width=50):
print(line)
fill(text, width=70)
पैराग्राफ को रैप करके सिंगल स्ट्रिंग (न्यूलाइन के साथ) लौटाता है।
print(textwrap.fill(sample_text, width=50))
# The textwrap module provides some convenience
# functions, as well as TextWrapper class that
# does all the work.
TextWrapper क्लास (अधिक नियंत्रण)
wrapper = textwrap.TextWrapper(
width=50,
initial_indent=" ",
subsequent_indent=" ",
break_long_words=False,
break_on_hyphens=True
)
print(wrapper.fill(sample_text))
उपयोगी पैरामीटर्स
| पैरामीटर | डिफ़ॉल्ट | विवरण |
|---|---|---|
| width | 70 | अधिकतम लाइन चौड़ाई |
| initial_indent | '' | पहली लाइन का इंडेंट |
| subsequent_indent | '' | बाद की लाइन्स का इंडेंट |
| expand_tabs | True | टैब्स को स्पेस में बदलें |
| replace_whitespace | True | व्हाइटस्पेस को स्पेस में बदलें |
| break_long_words | True | लंबे शब्द तोड़ें |
| break_on_hyphens | True | हाइफ़न पर ब्रेक करें |
| drop_whitespace | True | शुरुआत/अंत में व्हाइटस्पेस ड्रॉप करें |
अन्य फ़ंक्शन्स
shorten(text, width, placeholder='...'): टेक्स्ट छोटा करें।dedent(text): कॉमन लीडिंग व्हाइटस्पेस हटाएं (डॉकस्ट्रिंग्स के लिए उपयोगी)।indent(text, prefix): प्रत्येक लाइन में प्रीफिक्स जोड़ें।
उदाहरण: dedent
def my_function():
""" This is a docstring
with extra indentation.
"""
print(textwrap.dedent(__doc__))
my_function()
# This is a docstring
# with extra indentation.
उपयोग केस
- कंसोल आउटपुट फॉर्मेटिंग।
- रिपोर्ट/लॉग जनरेशन।
- डॉकस्ट्रिंग/मल्टीलाइन स्ट्रिंग क्लीनअप।
- UI टेक्स्ट रैपिंग।