Daniel
Daniel

Reputation: 23

Trying to do multiple tabs using \t

I'm trying to print a certain string each time on a new line and each line adding a new tab.

For example:

String
      String
           String

The code I used:

print(string + "\n\t" + string "\n\t" + string)

Which gives the output:

String
      String
      String

Can someone explain me why is it happening, and what are the ways to work around it?

Upvotes: 2

Views: 10452

Answers (3)

Tobias
Tobias

Reputation: 947

Considering you want to do this multiple times it is best to use a loop such as this:

n = 10 // amount of times you want to print
for x in range(n):
    tabs = "\t"*x
    print(tabs+"String"+"\n")

Upvotes: 0

Vasilis G.
Vasilis G.

Reputation: 7844

You can create a for loop and add a tab in each cycle:

number = 3
string = "String"
for i in range(number):
    print('\t' * i + string + '\n', end="")

Output:

String
    String
        String

You can use it for any positive value of variable number. You can also create a function that does the above:

def printTabbed(number,string):
    for i in range(number):
        print('\t' * i + string + '\n', end="")

And then call it:

printTabbed(3,"String")

Upvotes: 5

andersource
andersource

Reputation: 829

Use

print(string + "\n\t" + string "\n\t\t" + string)

In your code, the third line only contains one tab indent (indents don't "carry over" to the next lines, so you have to indent every line from the start).

Upvotes: 0

Related Questions