I would like to understand why this works fine:
>>> test_string = 'long brown fox jump over a lazy python'
>>> 'formatted "{test_string[0]}"'.format(test_string=test_string)
'formatted "l"'
Yet this fails:
>>> 'formatted "{test_string[-1]}"'.format(test_string=test_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> 'formatted "{test_string[11:14]}"'.format(test_string=test_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
I know this could be used:
'formatted "{test_string}"'.format(test_string=test_string[11:14])
...but that is not possible in my situation.
I am dealing with a sandbox-like environment where a list of variables is passed to str.format()
as dictionary of kwargs. These variables are outside of my control. I know the names and types of variables in advance and can only pass formatter string. The formatter string is my only input. It all works fine when I need to combine a few strings or manipulate numbers and their precision. But it all falls apart when I need to extract a substring.
f'formatted "{test_string[-1]}"'