textwrap.dedent()
istediğini yakındır ama sizin için ne istediğinizi uygulamıyor çünkü lider bir yeni hattı var.
def my_dedent(string):
if string and string[0] == '\n':
string = string[1:]
return textwrap.dedent(string)
Ancak textwrap.dedent()
sondaki nerede bir girinti satırlı açıklamada, Python kaynağını ürettiğini eğer Tamam özel bir şekilde sadece boşluk ile çizgiler kolları: Sen s
giden yeni satırı soyarak bir işlevde dedent
sarmak ya beyaz boşluk önemsizdir.
Ama genel olarak textwrap.dedent()
bu davranış undocumented and done with non-transparent regular expressions olduğunu, özellikle de, 'maksimum paragrafta' den fazla boşluk ile hatlarından Fazla boşlukları kaldırır tüm boşluk hatlarından boşluk kaldırır ve kapanış """
önce herhangi boşluk descards o uygunsuz .
Ayrıca boşluk aşağıdaki rutin kullanımı genellikle önemli olan olmayan Python kaynak kodu üretmek yana. Bu, TAB girintisini işlemez, ancak size, textwrap.dedent()
'un başarısız olduğu yeni satır olmadan, sorduğunuz çıktıyı verir.
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])
Bir varolduğunu bilmiyordum. Faydalı şeyler. +1. http://hg.python.org/cpython/file/2.7/Lib/textwrap.py 'arasında –
textwrap.dedent (s) 'bir satırsonu ile başlar ve OP tarafından istenmez. – Hubro
Kaynak kodu için gördüğüm en hızlı birikimi var – Jiri