Arash Saidi
Arash Saidi

Reputation: 2238

Print formatting to file in Python

I wish to write to a file in a formatted way. I have been searching how I can do this, and the best solution I have managed to get is this:

write_to_file.write('{:20} {:20} {:3}\n'.format(w[0][0], w[0][1], w[1]))

However, when I do this I do not get precise formatting.

det                  er                     6
er                   det                    5
den                  er                     5
du                   kan                    4
hva                  er                     3
har                  en                     3
er                   død                   3
å                   gjøre                 3
jeg                  vil                    3
har                  vi                     3
et                   dikt                   2
når                 du                     2
det                  var                    2
må                  være                  2
kan                  skrive                 2
hva                  gjør                  2
ha                   et                     2
jeg                  har                    2
du                   skal                   2
vi                   kan                    2
jeg                  kan                    2
en                   vakker                 2
er                   du                     2
når                 man                    2
får                 jeg                    2

I get things printed in the fashion above. I need everything to align perfectly.

Upvotes: 1

Views: 83

Answers (2)

user3613243
user3613243

Reputation: 93

The DataFrame command in the Pandas library would also be worth looking into.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

That's because you're still dealing with bytes. Once you start dealing with actual characters you'll find that they align perfectly.

write_to_file.write('{:20} {:20} {:3}\n'.format(u'å', u'gjøre', u'3'))

Upvotes: 2

Related Questions