1

So I'm trying to format a list in Python using the .format() method. I want my output to be as follows

One
    Two
        Three
            Four

However, when I run the following code

if __name__ == '__main__':
    output_str = ''
    my_list = ['One', 'Two', 'Three', 'Four']
    for element in my_list:
        output_str = '{}{}\n\t'.format(output_str, element)
    print (output_str)

It prints

One
    Two
    Three
    Four

Is there a way of making new lines in Python while keeping all tabs made before with .format()? Thanks for answering :)

2
  • 1
    Hint: multiply the string '\t' with the indendation level. Commented Nov 6, 2017 at 16:48
  • 1
    Works pretty good, Thanks :P. However, I still wonder if there's a way to do it directly with .format() without having to do such tricks Commented Nov 6, 2017 at 17:01

1 Answer 1

2

Yes, the .format() can be used to do the indentation by specifying the tab character as the fill character as follows:

my_list = ['One', 'Two', 'Three', 'Four']

for indent_level, element in enumerate(my_list):
    print("{:\t<{i}}{}".format('', element, i=indent_level))

This would display:

One
    Two
        Three
            Four
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.