Python 是否有用于取消缩进多行字符串的内置函数?
- 2025-01-21 09:01:00
- admin 原创
- 84
问题描述:
假设我有字符串
s = """
Controller = require 'controller'
class foo
view: 'baz'
class: 'bar'
constructor: ->
Controller.mix @
"""
现在,字符串中的每一行都有全局 4 个空格缩进。如果此字符串是在函数内部声明的,则它将具有 8 个空格全局缩进,等等。
Python 是否有一个函数可以删除字符串的全局左缩进?
我希望该函数输出是:
Controller = require 'controller'
class foo
view: 'baz'
class: 'bar'
constructor: ->
Controller.mix @"
解决方案 1:
不是内置函数,而是标准库中的函数: textwrap.dedent()
>>> print(textwrap.dedent(s))
Controller = require 'controller'
class foo
view: 'baz'
class: 'bar'
constructor: ->
Controller.mix @
解决方案 2:
我知道这个问题已经得到解答了,但还有这种方法:
import inspect
def test():
t = """
some text
"""
return inspect.cleandoc(t)
print(test())
解决方案 3:
textwrap.dedent()
接近您想要的,但它没有实现您要求的,因为它有一个前导换行符。您可以包装dedent
一个函数,从中删除前导换行符s
:
def my_dedent(string):
if string and string[0] == '
':
string = string[1:]
return textwrap.dedent(string)
但是textwrap.dedent()
,如果您从缩进多行语句生成 Python 源代码,则以特殊方式处理仅包含空格的行是可以的,其中尾随空格无关紧要。
但一般来说,textwrap.dedent()
从空格多于“最大缩进”的行中删除多余的空格、从所有空格行中删除空格以及丢弃结束之前的任何空格都是不合适的"""
,尤其是因为这种行为没有记录并且使用非透明的正则表达式完成。
由于我还生成非 Python 源代码,其中空格通常很重要,因此我使用以下例程。它不处理 TAB 缩进,但它确实为您提供了您要求的输出,而没有前导换行符,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] == '
':
s = s[1:]
lines = s.splitlines(True) # keep ends
max_spaces = -1
for line in lines:
if line != '
':
for idx, c in enumerate(line[:max_spaces]):
if not c == ' ':
break
max_spaces = idx + 1
return ''.join([l if l == '
' else l[max_spaces-1:] for l in lines])
解决方案 4:
我可以通过回车来做到这一点:
s = """
Controller = require 'controller'
class foo
view: 'baz'
class: 'bar'
constructor: ->
Controller.mix @
"""
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD