textwrap.dedent()
आप क्या चाहते हैं के करीब है , लेकिन यह आपके द्वारा मांगी गई चीज़ों को लागू नहीं करता है, क्योंकि इसकी एक अग्रणी नई लाइन है।
def my_dedent(string):
if string and string[0] == '\n':
string = string[1:]
return textwrap.dedent(string)
हालांकि textwrap.dedent()
विशेष तरीके से सिर्फ खाली स्थान के यह ठीक है अगर आप एक मांगपत्र बहु बयान से अजगर स्रोत पैदा कर रहे हैं, जहां पूर्ण विराम वाले लाइनों संभालती है: आप एक समारोह है कि s
से प्रमुख न्यू लाइन स्ट्रिप्स में dedent
लपेट कर सकते हैं या तो व्हाइटस्पेस महत्वहीन है।
लेकिन सामान्य रूप में यह अनुचित है कि textwrap.dedent()
, 'अधिकतम मांगपत्र' से अधिक सफेद स्थान के साथ लाइनों से अतिरिक्त व्हाइट को हटा सभी खाली स्थान के लाइनों से खाली स्थान के दूर करता है और यह बंद करने """
से पहले किसी भी खाली स्थान के descards कि, खासकर जब से इस व्यवहार undocumented and done with non-transparent regular expressions है ।
चूंकि मैं गैर-पायथन स्रोत कोड भी उत्पन्न करता हूं जहां रिक्त स्थान अक्सर महत्वपूर्ण होते हैं, मैं निम्नलिखित दिनचर्या का उपयोग करता हूं। यह टैब इंडेंटेशन को संभाल नहीं करता है, लेकिन यह आपको आउटपुट देता है जो आपने बिना किसी नई न्यूलाइन के पूछा है, जहां textwrap.dedent()
विफल रहता है।
def remove_leading_spaces(s, strict=False):
'''Remove the maximum common spaces from all non-empty lines in string
Typically used to remove leading spaces from all non-empty lines in a
multiline string, preserving all extra spaces.
A leading newline (when not useing '"""\') is removed unless the strict
argument is True.
Note that if you want two spaces on the last line of the return value
without a newline, you have to use the max indentation + 2 spaces before
the closing """. If you just input 2 spaces that is likely to be the
maximum indent.
'''
if s and not strict and s[0] == '\n':
s = s[1:]
lines = s.splitlines(True) # keep ends
max_spaces = -1
for line in lines:
if line != '\n':
for idx, c in enumerate(line[:max_spaces]):
if not c == ' ':
break
max_spaces = idx + 1
return ''.join([l if l == '\n' else l[max_spaces-1:] for l in lines])
मुझे नहीं पता था कि कोई अस्तित्व में है। उपयोगी सामान +1। –
यह ऊपर दिए गए वोटों का सबसे तेज़ संचय है जिसे मैंने कभी जवाब के लिए देखा है – Hubro
यहां समर्पण का स्रोत कोड: http://hg.python.org/cpython/file/2.7/Lib/textwrap.py – Jiri