How to remove extra indentation of Python triple quoted multi-line strings?

后端 未结 6 1049
野的像风
野的像风 2020-12-23 14:46

I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The proble

6条回答
  •  北海茫月
    2020-12-23 15:02

    Showing the difference between textwrap.dedent and inspect.cleandoc with a little more clarity:

    Behavior with the leading part not indented

    import textwrap
    import inspect
    
    string1="""String
    with
    no indentation
           """
    string2="""String
            with
            indentation
           """
    print('string1 plain=' + repr(string1))
    print('string1 inspect.cleandoc=' + repr(inspect.cleandoc(string1)))
    print('string1 texwrap.dedent=' + repr(textwrap.dedent(string1)))
    print('string2 plain=' + repr(string2))
    print('string2 inspect.cleandoc=' + repr(inspect.cleandoc(string2)))
    print('string2 texwrap.dedent=' + repr(textwrap.dedent(string2)))
    

    Output

    string1 plain='String\nwith\nno indentation\n       '
    string1 inspect.cleandoc='String\nwith\nno indentation\n       '
    string1 texwrap.dedent='String\nwith\nno indentation\n'
    string2 plain='String\n        with\n        indentation\n       '
    string2 inspect.cleandoc='String\nwith\nindentation'
    string2 texwrap.dedent='String\n        with\n        indentation\n'
    

    Behavior with the leading part indented

    string1="""
    String
    with
    no indentation
           """
    string2="""
            String
            with
            indentation
           """
    
    print('string1 plain=' + repr(string1))
    print('string1 inspect.cleandoc=' + repr(inspect.cleandoc(string1)))
    print('string1 texwrap.dedent=' + repr(textwrap.dedent(string1)))
    print('string2 plain=' + repr(string2))
    print('string2 inspect.cleandoc=' + repr(inspect.cleandoc(string2)))
    print('string2 texwrap.dedent=' + repr(textwrap.dedent(string2)))
    

    Output

    string1 plain='\nString\nwith\nno indentation\n       '
    string1 inspect.cleandoc='String\nwith\nno indentation\n       '
    string1 texwrap.dedent='\nString\nwith\nno indentation\n'
    string2 plain='\n        String\n        with\n        indentation\n       '
    string2 inspect.cleandoc='String\nwith\nindentation'
    string2 texwrap.dedent='\nString\nwith\nindentation\n'
    

提交回复
热议问题