Slicing strings in str.format
No, you can't apply slicing to strings inside a the replacement field.
You'll need to refer to the Format Specification Mini-Language; it defines what is possible. This mini language defines how you format the referenced value (the part after the :
in the replacement field syntax).
You could do something like this.
NOTE
This is a rough example and should not be considered complete and tested. But I think it shows you a way to start getting where you want to be.
import string
class SliceFormatter(string.Formatter):
def get_value(self, key, args, kwds):
if '|' in key:
try:
key, indexes = key.split('|')
indexes = map(int, indexes.split(','))
if key.isdigit():
return args[int(key)][slice(*indexes)]
return kwds[key][slice(*indexes)]
except KeyError:
return kwds.get(key, 'Missing')
return super(SliceFormatter, self).get_value(key, args, kwds)
phrase = "Hello {name|0,5}, nice to meet you. I am {name|6,9}. That is {0|0,4}."
fmt = SliceFormatter()
print fmt.format(phrase, "JeffJeffJeff", name="Larry Bob")
OUTPUT
Hello Larry, nice to meet you. I am Bob. That is Jeff.
NOTE 2
There is no support for slicing like [:5]
or [6:]
, but I think that would be easy enough to implement as well. Also there is no error checking for slice indexes out of range, etc.