jtaylor94
jtaylor94

Reputation: 137

Python Fully justifying string

Does anyone have a nice concise way of fully justifying a string for a given line width like this:

The cat sat on the mat, the cat
sat on the mat, the  cat sat on
mat, the cat sat on the mat the
mat,  the cat  sat on  the  mat
the cate sat on the mat...

So that edges are straight on both sides. The function takes in a string and a line width and returns a string in the above format. There are Python functions for left, right and centre but not justified. I have a method but its a bit too long.

Thanks!

JT

Upvotes: 2

Views: 2053

Answers (1)

RichieHindle
RichieHindle

Reputation: 281855

Here's a recipe in the ActiveState Python Cookbook for exactly that:

"Align string with spaces between words to fit specified width"

Upvotes: 3

Related Questions