简体   繁体   中英

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

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. Eg: 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)


 *if digit % 2 == 0: <--- Error message
    TypeError: not all arguments converted during string formatting*

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

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)

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:
...

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)

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM