tekknolagi
tekknolagi

Reputation: 11012

text aligning, python

How could I align the text so that it cuts the first 140 characters of a string, and fills the rest with whitespace?

e.g. "%140s"%some_text but the space on the other side.

Thoughts?

Upvotes: 0

Views: 713

Answers (2)

sleeplessnerd
sleeplessnerd

Reputation: 22761

You can also use rjust and ljust for strings. In combination with slicing you get this:

>>> "blabla"[:10].ljust(10)
'blabla    '
>>> "blabla12345678901234567890"[:10].ljust(10)
'blabla1234'
>>> 
>>> "blabla"[:10].rjust(10)
'    blabla'
>>> "blabla12345678901234567890"[:10].rjust(10)
'blabla1234'
>>> 

This is quickly understood by someone reading the code, but the string formatting variant is much more concise.

Upvotes: 3

Ned Batchelder
Ned Batchelder

Reputation: 375574

Simple: "%-140.140s" % some_text

Upvotes: 6

Related Questions