Skeptic
Skeptic

Reputation: 115

Print with automatic tab (Python)

Is there some simple command or way -- let's call it \magic -- so that having

print('Hello!\magicHello!')

produces the follwing

Hello!
      Hello!

That is, it makes the next line be indented precisely to the end of the previous?

Many thanks!

Upvotes: 0

Views: 1097

Answers (2)

Bunyk
Bunyk

Reputation: 8067

You could do that by wrapping string in function:

def magic(s):
    res, indent = [], 0
    for part in s.split('\magic'):
        res.append(' ' * indent + part)
        indent += len(part)
    return '\n'.join(res)

print magic('Hello!\magicHello!')

Which produces:

Hello!
      Hello!

Upvotes: 3

seaotternerd
seaotternerd

Reputation: 6419

There is a tab character ("\t"), and there are various things that you can do with justification and padding, but I don't think that there's a way to get the precision you want without it being more cumbersome than the straightforward solution:

printstring = "Hello!"
print(printstring+"\n"+len(printstring)*" " + printstring)

EDIT:

If you have a list of words that you want to print this way, you can do the following:

words = ["This", "is", "a", "test"]
for i in range(len(words)):
    print(sum([len(w) for w in words[:i]])*" " + words[i])

It's a little cumbersome, but it should work.

Upvotes: 1

Related Questions