Home > Software engineering >  Python: Convert Float to Int in List
Python: Convert Float to Int in List

Time:02-19

I'm trying to retrieve values from a list, and if the value can be converted to int, I want to store the value as int in a string. For this, I have tried to use int() and try...except blocks, but still my is not getting converted to int.

My code:

_number_of_alphabets, _number_of_numbers, _number_of_special_characters = ranges(_size,_number_of_alphabets,_number_of_numbers,_number_of_special_characters)
    _list = alphabets(_number_of_alphabets)
    _list = append(_list,numbers(_number_of_numbers))
    _list = append(_list,special_characters(_number_of_special_characters))
    shuffle(_list)
 
    _password = ''
 
    for i in _list:
        try:
            _password =int(i)
        except:
            _password =i
    
    return _password

Can anyone please help me to understand, how should I modify my code so that _password store the list items that can be converted to int as int and store remaining values as it is

CodePudding user response:

Please try to provide full error traceback documentation in future posts to help people better assist you.

It's fundamentally impossible to concatenate type int to a str initialization unless you cast the int as a str (i.e., the opposite of what you're trying to do). I'm not really sure what your end goal is here, but I can assure you that the problem is not that the strings which you are trying to cast as integers are not being converted (in the case where they are numbers in string form), it's rather just that you can't concatenate them to an empty string.

If there's something else you're trying to do here, I can try to help if you can elaborate.

CodePudding user response:

L = [some float numbers separated by comma]
New_l = []
for I in L:
    New_l.append(int(I)) 

Code is pretty much self explanatory

  • Related