3

Everyone, hello!

I'm not able to count properly, and I'm at a loss. A second pair of eyes would really be helpful.

I'm getting a variable from my config file as:

import ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.ini")
count1 = config.get('Counter','count1')
>>> print count1
5

However, when I want to simply substract - 1 from this variable, as so:

count1 = (count1 - 1)

I'm confronted with an error:

TypeError: unsupported operand type(s) for -: 'str' and 'int'

Any help would be really appreciated. Thanks!

1
  • 1
    You are obviously trying to do a substraction of a str and an int, as the error message tells you. Since 1 is an int, then count1 must be a str. You can print type(count1) before the line that gives you the error to make sure of that. Then, just convert it with int(). Commented Oct 20, 2016 at 7:08

2 Answers 2

4

You can't do arithmetic with strings, you have to convert it first to an integer with the int function:

count1 = int(config.get('Counter', 'count1'))

You could also use the config.getint or config.getfloat methods.

If you need a float, you can use the float function instead.

Sign up to request clarification or add additional context in comments.

Comments

3
>>> count1 = config.get('Counter','count1')

Above will simply return a string type. And, that's why you are getting the error because you can't subtract an int from a string type.

If you need int from config, you can use RawConfigParser.getint method:

>>> count1 = config.getint('Counter','count1')

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.