Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to get the sum of the digits of an integer, and found the solutions below:
sum(map(int,list(str(123))))
sum(int(digit) for digit in str(123))
However, when I run this, I get the below error:
TypeError: 'int' object is not callable
Contrary to other answers, both your code works fine.
I think you are shadowing something on your code. Perhaps you used int as a variable?
sum() works on iterables.
int(digit) for digit in str(123)
This returns an generator, and should work, as said by other answers, take a look at this answer.
The below should also do the job:
sum([int(digit) for digit in '123'])
Hope this helps!
sum(int(digit) for digit in str(123))
The above code should work.
However you said you get the error,
TypeError: 'int' object is not callable
That error suggests that you're using type int instead of a str
.
Did you use another variable for that?
For example, the below code should give you that error you mentioned
obj = 123
sum(int(digit) for digit in obj)
You have to ensure that obj is of a str type.
sum() works in iterable objects. You need to create a list with the digits you are trying to add. The code below should do that:
sum([int(x) for x in str(123)])
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I have this code that errors out in python3:
self.instance_id = get_instance_metadata(data='meta-data/instance-id').keys()[0]
TypeError: 'dict_keys' object is not subscriptable
I changed my code and I get different error (I guess I need more experience):
self.instance_id = get_instance_metadata(list(data='meta-data/instance-id').keys())[0]
TypeError: list() takes no keyword arguments
.keys() is a set-like view, not a sequence, and you can only index sequences.
If you just want the first key, you can manually create an iterator for the dict (with iter) and advance it once (with next):
self.instance_id = next(iter(get_instance_metadata(data='meta-data/instance-id')))
Your second attempt was foiled by mistakes in where you performed the conversion to list, and should have been:
self.instance_id = list(get_instance_metadata(data='meta-data/instance-id').keys())[0] # The .keys() is unnecessary, but mostly harmless
but it would be less efficient than the solution I suggest, as your solution would have to make a shallow copy of the entire set of keys as a list just to get the first element (big-O O(n) work), where next(iter(thedict)) is O(1).
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
adding = int(5+3)
subtract = int(10-2)
multiplication = int(2*4)
division = int(16/2)
print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))
im getting a typeError: TypeError: str() takes at most 3 arguments (7 given)
Solution:
Just change this piece of code from this
print (str(adding,"\n",subtract,"\n",multiplication,"\n",division))
To this.
print (adding,"\n",subtract,"\n",multiplication,"\n",division)
Reason: str() is a typecast method. You don't need to typecast each and everything.
For Reference:
https://www.geeksforgeeks.org/type-casting-in-python-implicit-and-explicit-with-examples/
Think of str as a function that takes in a variable and converts it into a string. Passing multiple variables to str() separated by comma will not apply string function to each variable. It will instead mean that they are arguments to the function.
If you want to convert each variable into
adding = str(int(5+3))
subtract = str(int(10-2))
multiplication = str(int(2*4))
division = str(int(16/2))
print (adding,"\n",subtract,"\n",multiplication,"\n",division)
Note that print function accepts multiple arguments for printing purposes.
To convert an integer to string, you need to use str() each variables separately.
Also, you can use + as concat operator to avoid extra space.
print(str(adding)+"\n"+str(subtract)+"\n"+str(multiplication)+"\n"+str(division))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have used str as a variable. Now, I would like to convert an int into a string. For this, normally I would use str(10). What should I do in this case?
You can just delete the variable to get str() back:
othervarname = str
del str
Find and replace "str" with "sensibleNameForYourVariable", then use str(i) to convert integers to strings.
Use the code below if you had used str as a variable. This will solve your problem. The keyword str() internally uses __str__() function so better use that function only
str = 1
str.__str__()
Output
'1'
As in your case you should use.
Retrieve it from __builtins__.
str = "shadowed"
assert __builtins__.str(3) == "3"
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have the following Python code to iterate over a nested dictionary and grab a value from the second child:
ret = some_dict
for item, val in ret.items():
for item2, val2 in val.items():
print val2['result']
When I test this in IPython or the interactive Python interpreter, the code works fine, and prints the value of val2['result'] for each item in the dictionary. However, when I use this block of code in a Python program I get the following error when trying to print val2['result']:
TypeError: string indices must be integers, not str
If I print json.dumps(val2, indent=2), I can see that the dictionary is formed correctly. Attempting to use dict() to cast val2 to a dictionary in the script also fails with the following error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I'm not entirely sure what I'm doing wrong at this point, since the code works in the interactive interpreter. I am using Python 2.7.6, and the use case is iterating over a dictionary returned by the Saltstack Python client.
Believe the message: it is telling you that val2 is a string when you think it is a dict. This is almost certainly due to your JSON data not being structured as you think it is.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
For some reason this piece of script is returning the error: "TypeError: string indices must be integers"; and I cannot see what's wrong. Am I being stupid and overlooking an obvious mistake here? I can't see one for the life of me!
terms = {"ALU":"Arithmetic Logic Unit"}
term = input("Type in a term you wish to see: ")
if term in terms:
definition = term[terms]
sentence = term + " - " + definition
print(sentence)
else:
print("Term doesn't exist.")
I think you want it this way: definition = terms[term]
This line definition = term[terms] is trying to get a character out of the string term. You probably just typoed, and want
definition = terms[term]
^ here, reference the dict, not the string
You are indexing the string term instead of the dictionary terms. Try:
definition = terms[term]
You accidentally swapped the variables. Change this:
definition = term[terms]
To this:
definition = terms[term]