I have a list of strings, the list contains numbers and words. to keep it simple, I want to be able to take an element from the list, see if the element is a str, float, or int, and then convert it as such. Of course all of the elements in the list are currently a string, so how do I check what the type ‘should’ be and then convert it to such?
btw, the list was read from a text file, it contains the name of an object, it’s properties, and the properties value, just to tie this thread in with it’s title.
It is quite possible that I am wrong, but I don’t know that it is possible to “detect” directly what type a variable should be. If this is the case, it would seem to me that you might want to use the “try” statement. Due to the fact that the variables are already strings, I would do somthing like:
var = list[item]
var = float(item)
pass #Not a float (therefore can't be an int). It must be a string.
Again, I could be a complete idiot. But I feel as if this should give you (sort of) the results that you want.
In reality, it would be better to have a consistent format for the save file (.ini files are perfect for what you want). Best of luck! :yes:
Thanks for the response kendrick. The try statement idea seems the most logical so I’ll give that a go, I’ll also look into .ini files. Thanks again
This will help me out, thanks for the .ini suggestion
AWESOME! your try statement idea totally worked, no need to learn the config parser.
A) Never ever catch ALL errors. Catch errors you are expecting. Otherwise you will hide errors you are not expecting too. This will result in very hard to discover problems, when you got such an error (e.g. an attribute error). Recommendation: Add the Error Type to the except statement (end never suggest to use it without)
B) The way you convert does not necessarily produce the data you are expecting. E.g. you can convert “1” into float and integer. That are two different data types. This can be fine but strongly depends on the specific situation.
C) Better use existing libraries such as pickle, Python or json rather than reinventing the wheel.
Knowing this it leads to the question: Why do you have a list of strings rather than a list of objects of the required type? I mean what is the reason to make them strings first?