19
1
When coding in Python, sometimes you want a multiline string within a function, e.g.
def f():
s = """\
Line 1
Line 2
Line 3"""
(The backslash is to remove a leading newline)
If you try to actually print out s
, however, you'll get
Line 1
Line 2
Line 3
That's not what we want at all! There's too much leading whitespace!
The challenge
Given a multiline string consisting of only alphanumeric characters, spaces and newlines, remove all common spaces from the beginning of each line. Each line is guaranteed to have at least one non-space character, and will have no trailing spaces. The output may not have extraneous whitespace, whether it be before or after the entire output or an individual line (with the exception of a single optional trailing newline).
Input may be via STDIN or function argument, and output may be via STDOUT or function return value. You cannot use any builtins which are designed to dedent multiline strings or perform this exact task, e.g. Python's textwrap.dedent
.
This is code-golf, so the solution in the fewest bytes wins. Standard loopholes apply.
Test cases
"a" -> "a"
" abc" -> "abc"
" abc\n def\n ghi" -> " abc\ndef\n ghi"
" a\n b\n c" -> "a\nb\nc"
" a\n b\n c\nd" -> " a\n b\n c\nd"
" a b\n c d\n e f" -> "a b\n c d\n e f"
For example, the last test case is
a b
c d
e f
and should look like this after stripping leading spaces:
a b
c d
e f
May the output have trailing whitespace? – orlp – 2015-07-16T14:07:51.200
@orlp No it may not, will clarify. – Sp3000 – 2015-07-16T14:10:15.177