If there is a variable a whose type is unknown until it is created, how to account for the type when using python string formatting, specifically at the time of formatting?
Example:
import numpy as np
import datetime as dt
a = dt.datetime(2020,1,1)
print(f'{a:%d/%m/%Y}')
>>>
01/01/2020
However if the variable is changed, then this will produce an error:
a = np.nan
print(f'{a:%d/%m/%Y}')
>>>
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-70-02594a38949f> in <module>
1 a = np.nan
----> 2 print(f'{a:%d/%m/%Y}')
ValueError: Invalid format specifier
So I am attempting to implement something like:
print(f'{a:%d/%m/%Y if not np.isnan(a) else ,.0f}')
>>>
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-78-52c24b6abb16> in <module>
----> 1 print(f'{a:%d/%m/%Y if not np.isnan(a) else ,.0f}')
ValueError: Invalid format specifier
However, as we can see it attempts to format the variable before evaluating the expression. Perhaps the syntax needs correcting or another approach is required entirely. However, I do specifically want to evaluate which formatter to deploy it and deploy it at the time of printing the f-string.
Thanks!
Realise that the following approach is possible:
print(f'{a:%d/%m/%Y}' if isinstance(a,dt.datetime) else f'{a}')
However, the syntax is still too cumbersome, especially if this is to be deployed in mutliple locations. Effectively am searching for a streamlined way to format the variable if it is of a compatible type to the format and if not, then default to no specified formatter.
Thanks!