[melbourne-pug] string formatting / Format SPecific Mini Language
Josh Bode
joshbode at gmail.com
Tue May 13 11:43:04 CEST 2014
This is much more obvious and clear than my solution (which looks like an emoticon gone wrong), and from a quick test, at least twice as fast on small strings ~ 80 characters - and gets even better on long strings (not that speed’s probably a huge factor here)
In IPython:
In [1]: something = 'A' * 40
In [2]: %timeit something.ljust(80)
1000000 loops, best of 3: 439 ns per loop
In [3]: %timeit "{0:<{1}}".format(something, 80)
1000000 loops, best of 3: 876 ns per loop
In [4]: %timeit something.ljust(10000)
1000000 loops, best of 3: 867 ns per loop
In [5]: %timeit "{0:<{1}}".format(something, 10000)
100000 loops, best of 3: 2.4 µs per loop
On 2014-05-13, at 5:17 pm, Tom Dunham <tom at tomdunham.org> wrote:
> String has an 'ljust' method that left-justifies the string in a column of a given length, so you could do:
>
> some_string = something.ljust(len(some_other_string))
>
> (I'm on the train so I can't run this to check, but I'm pretty sure that's correct).
>
> Cheers,
> Tom
>
> On 13 May 2014 07:27, "David Crisp" <dcrisp at netspace.net.au> wrote:
> I need to create a string that has a variable length of padding and im not sure how to do it.
>
> For instance
>
> some_string = ("{something:<40}".format(something = somethingelse))
>
> will give me a 40 space padded display of something
>
>
> What if, after a little bit of string concatination (for want of a abetter word) I want to do the following:
>
> string_length = len(some_other_string)
>
> some_string = ("{something:<string_length}".format(something = somethingelse))
>
> When I do this I get a ValueError: Invalid format specifier.
>
> IS there a clean and neat way of doing the above?
>
> Regards,
> David Crisp
>
>
>
>
> _______________________________________________
> melbourne-pug mailing list
> melbourne-pug at python.org
> https://mail.python.org/mailman/listinfo/melbourne-pug
> _______________________________________________
> melbourne-pug mailing list
> melbourne-pug at python.org
> https://mail.python.org/mailman/listinfo/melbourne-pug
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/melbourne-pug/attachments/20140513/7ff955d3/attachment.html>
More information about the melbourne-pug
mailing list