jeudi 30 juin 2016

Left truncate using python 3 str.format?


Q: Is is possible to create a format string using Python 3's string formatting syntax to left truncate?

Basically what I want to do is take a git SHA:

"c1e33f6717b9d0125b53688d315aff9cf8dd9977"

And using only a format string, get the display only the right 8 chars:

"f8dd9977"

Things Ive tried:

Invalid Syntax

>>> "{foo[-8]}".format(foo="c1e33f6717b9d0125b53688d315aff9cf8dd9977")  
>>> "{:8.-8}".format("c1e33f6717b9d0125b53688d315aff9cf8dd9977")

Wrong Result

### Results in first 8 not last 8. 
>>> "{:8.8}".format("c1e33f6717b9d0125b53688d315aff9cf8dd9977")

Works but inflexible and cumbersome

### solution requires that bar is always length of 40.
>>> bar="c1e33f6717b9d0125b53688d315aff9cf8dd9977"
>>> "{foo[32]}{foo[33]}{foo[34]}{foo[35]}{foo[36]}{foo[37]}{foo[38]}{foo[39]}".format(foo=bar)

A similar question was asked, but never answered. However mine differs in that I am limited to using only format string, I don't have the ability to change the range of the input param.


Aucun commentaire:

Enregistrer un commentaire