简体   繁体   中英

ValueError: invalid literal for int() with base 10 for my string

I am trying to compare two strings within an if-else statement in python. My code is the following:

#_file = 'tests_1012_IEO_ANG_HI.pk'
_prts = _file.split("_") # _prts  = ['test', '1012', 'IEO', 'ANG', 'HI.pkl']
if (_prts[3] == "HAP"):
        label = 1
elif (_prts[3] == "SAD"):
        label = 2
elif (_prts[3] == "ANG"):
        label = 3

The _file variable is a string and by splitting it I am taking its substrings ['test', '1012', 'IEO', 'ANG', 'HI.pkl'] while the _file = 'tests_1012_IEO_ANG_HI.pk'

if (_prts[3] == "HAP"):

However, when I am trying to use the above if-else statement I am receiving the following error:

if (_prts[3] == "HAP"): ValueError: invalid literal for int() with base 10: 'ANG'

What is exactly going on? I have checked the following code in debugging _prts[3] == "ANG" and the result is True . Why am I receiving this error?

try if "HAP" in _prts[3]

Edit: I tried your code with your values _file = "asdfads_afsd_fads_ANG_adfs" and it worked fine (python 3.8.1)

It's hard to tell you what's the problem without knowing what is the real content in _prts.

What I would try to use is str(), as follows:

_prts = _file.split("_")
if (str(_prts[3]) == "HAP"):
        label = 1
elif (str(_prts[3]) == "SAD"):
        label = 2
elif (str(_prts[3]) == "ANG"):
        label = 3

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