Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an operator that can trim indentation in multi-line string?

This is really nice in Groovy:

println '''First line,
           second line,
           last line'''

Multi-line strings. I have seen in some languages tools that take a step further and can remove the indentation of line 2 and so, so that statement would print:

First line,
second line,
last line

and not

First line,
           second line,
           last line

Is it possible in Groovy?

like image 402
Binders Lachel Avatar asked Mar 09 '14 09:03

Binders Lachel


People also ask

How to format multiline string in Python?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.

How do you remove an indent from a string in Python?

Use textwrap.Call textwrap. dedent(s) to remove indentation from s .

Does groovy care about indentation?

Groovy is indentation-unaware, but it's good engineering practice to follow the usual indentation schemes for blocks of code. Groovy is mostly unaware of excessive whitespace, with the exception of line breaks that end the current statement and single-line comments.

How to indent in Python strings?

You can indent the lines in a string by just padding each one with proper number of pad characters. This can easily be done by using the textwrap. indent() function which was added to the module in Python 3.3.


1 Answers

You can use stripMargin() for this:

println """hello world!
        |from groovy 
        |multiline string
    """.stripMargin()

If you don't want leading character (like pipe in this case), there is stripIndent() as well, but string will need to be formatted little differently (as minimum indent is important)

println """
        hello world!
        from groovy 
        multiline string
    """.stripIndent()

from docs of stripIndent

Strip leading spaces from every line in a String. The line with the least number of leading spaces determines the number to remove. Lines only containing whitespace are ignored when calculating the number of leading spaces to strip.


Update:

Regarding using a operator for doing it, I, personally, would not recommend doing so. But for records, it can be done by using Extension Mechanism or using Categories (simpler and clunkier). Categories example is as follows:

class StringCategory {
    static String previous(String string) { // overloads `--`
        return string.stripIndent()
     }
}

use (StringCategory) {
    println(--'''
               hello world!
               from groovy 
               multiline string
           ''') 
}
like image 148
kdabir Avatar answered Oct 25 '22 22:10

kdabir