Python print indentations
Asked Answered
C

5

5

In Python 3.x how do you print an indent of white space, the method I am looking for looked something like this

level = 3
print ('% indent symbol' % * level, 'indented text')

should print:

            indented text

repeating answer from below: thanks to @sudo_coffee for \t

print ('\t' * level, 'indented text')

or maybe:

print ((' ' * 4) * level, 'indented text')
Condensation answered 5/4, 2017 at 13:12 Comment(1)
Apart from the syntax error, what's the problem here?Furze
C
9

sorry guys, think I found the answer, thanks to @sudo_coffee for \t

print ('\t' * level + 'indented text')

or maybe:

print ((' ' * 4) * level + 'indented text')
Condensation answered 5/4, 2017 at 13:18 Comment(0)
Y
2
level = 3
print (" "*level, 'indented text')
Yovonnda answered 5/4, 2017 at 13:16 Comment(0)
S
1

To indent, or enter a "tab" amount of space, use the escape sequence \t.

level = 3
print ('\t indented text')
Shikoku answered 5/4, 2017 at 13:14 Comment(1)
I have found the answer: print ('\t' * level, 'indented text')Condensation
W
0
level = 3
indented_symbol = "    "

print '{} Indented text'.format(indented_symbol*level)
Weltpolitik answered 5/4, 2017 at 13:18 Comment(0)
C
0

Python has an inbuilt module for this, textwrap, with the advantage that it will handle multiline strings (useful for printing error messages etc):

import textwrap

level = 3
print(textwrap.indent('indented text\nwith linebreaks', level * '    '))

Outputs:

            indented text
            with linebreaks
Carse answered 19/7 at 9:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.