How to fix 'TypeError: not all arguments converted during string formatting' in Python

Question:

I’m trying to make a code to get two keys from a master key. The key must be a string. For the first, you have to take the even number and for the second, the odds numbers. E.g.: Master key = 18923. First Key = 82, second Key = 193.

I am new to python.

masterKey = '18293'
firstKey = ''
secondKey = ''

masterKeyList = list(masterKey)
firstKeyList = list(firstKey)
secondKeyList = list(secondKey)

for digit in masterKeyList:
    if digit % 2 == 0:  # <--- here is the error
        firstKeyList.append(digit)
    else:
        secondKeyList.append(digit)

Error message

TypeError: not all arguments converted during string formatting

I want to know why this happens, and a solution. Thank you!

Asked By: Knarf

||

Answers:

This error is occurring because digit is a string, and % in the context of strings is a format operator.

To fix it, convert it into an integer:

...
if int(digit) % 2 == 0:
...
Answered By: iz_

digit is a string in your code, so if you want to apply modulo 2 you need to convert it to a number. That should work fine:

masterKey = '18293'
firstKey = ''
secondKey = ''

masterKeyList = list(masterKey)
firstKeyList = list(firstKey)
secondKeyList = list(secondKey)

for digit in masterKeyList:
    if int(digit) % 2 == 0: <--- fixed
        firstKeyList.append(digit)
    else:
        secondKeyList.append(digit)
Answered By: Guimoute

digit is a string. Just typecast it using int():

if not int(digit) % 2:

The reason your error is occurring is because the modulus operator is also a string formatting operator, but you haven’t provided the necessary arguments to string-format ‘2’

This for-loop will work:

for digit in masterKeyList:
    if not int(digit) % 2:
        firstKeyList.append(digit)
    else:
        secondKeyList.append(digit)
Answered By: Alec

This can be simplified and shortened using list comprehension and join() if you need strings. In case you prefer lists then just remove the join(). You can do something like the following:

masterKey = '18293'
firstKey  = "".join([e for e in masterKey if int(e) % 2 == 0])
secondKey = "".join([e for e in masterKey if int(e) % 2 != 0])
Answered By: SuperKogito
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.