3

I'm trying to handle a dataset containing only str, but the values of the str can be either real text or something like "1.0" and "3.54".

I want to convert all string to the best possible type, which means 1.0 should be converted to int, 3.54 should be converted to float and everything else should stay str.

What is the best way to do so?

1
  • 2
    The string "1.0" is clearly meant to represent a floating point number (even though one with an integer value) - why would you not want to convert it to float? Commented Aug 11, 2020 at 15:46

4 Answers 4

3

lets try

def convert(txt): try: k = float(txt) if k%1 ==0: return int(k) return k except ValueError: return txt 

now what I'm thinking is, the input is either a number or not, anyway we can float it. if it is also divisable by 1 its an int and we're done. if it isn't then it is a float after all and we're done. any other case: there's nothing that we can do, and then let's return it

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a try except block to perform the operation.

for s in string: try: //convert to int or float except: pass 

1 Comment

I don't think your answer addresses exactly what is being asked. You should convert to int or float but those specifics is what the user is asking for.
0

You may use

strings = ["some weird junk", "1.0", "2.345", -1000] for string in strings: try: number, decimal = string.split(".") try: if decimal == "0": value = int(number) else: value = float(string) except: value = string except (ValueError, AttributeError): try: value = int(string) except ValueError: value = string print(value, type(value)) 

Which yields

some weird junk <class 'str'> 1 <class 'int'> 2.345 <class 'float'> -1000 <class 'int'> 

Comments

0
def convert(string): possible = [str, int, float] for func in possible: try: result = func(string) except ValueError: continue if str(result) == string and type(result) is not str: return result return string strings = ['hello', '1', '1.0', '1.9'] for string in strings: result = convert(string) print(type(result), result) 
Output: <class 'str'> hello <class 'int'> 1 <class 'float'> 1.0 <class 'float'> 1.9 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.