0

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?

2 Answers 2

6

Simple: "%-140.140s" % some_text

Sign up to request clarification or add additional context in comments.

6 Comments

Python is so brilliantly simple...!
>>> x = "abcd" -- >>> "%-2s"%x -- 'abcd'
@Constantinius i believe the value needs to be greater than the length of the string
@Constantinius see the new answer
Note how this took an iteration to get right, the stringformat syntax is a little too cryptic for my taste in complex cases.
|
3

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.

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.