2

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?

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.