Search code examples
pythonstringtypeerrorf-string

TypeError within f-string expression - 'str' object is not callable


I am getting an error when I try to compose a string using f-string syntax in Python 3.7.

My code is the following:

i = 1

site_id= 0
meter = 0
model_id = i
target_name = 'log1p_meter_reading_corrected2'

f'model_site_id_{str(site_id)}_meter_{str(meter)}_{target_name}_model_id_{str(model_id)}_11_12_19.hdf5'

which returns the error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-1ebe1c78d868> in <module>
      6 target_name = 'log1p_meter_reading_corrected2'
      7 
----> 8 f'model_site_id_{str(site_id)}_meter_{str(meter)}_{target_name}_model_id_{str(model_id)}_11_12_19.hdf5'

TypeError: 'str' object is not callable

What creates the error and how should I correct my code?


Solution

  • In f-strings you don't need to wrap the variable with str(). The following should work:

    f'model_site_id_{site_id}_meter_{meter}_{target_name}_model_id_{model_id}_11_12_19.hdf5'
    

    However, your code should technically work fine, the str() calls are just redundant - you have probably reassigned the reserved keyword str at some point by doing something like:

    str = 'test'
    

    Now, if we do

    >>> str(site_id)
    

    We get

    TypeError: 'str' object is not callable