0

I wander if there is a simple way to convert a string to a number, knowing that the string begins with numbers but can contain non numerical characters. For example: my_str = "36.12minuts"

I remember a function in Visual Basic that does the conversion directly :

my_str = "36.12minuts"
val(my_str) => 36.12

How about Python?

Taha
  • 709
  • 5
  • 10
  • I recall that the functions int(.), float(.) and int(float(.)) do not work unless there is only a numerical value in the string. – Taha Jul 17 '14 at 08:47

1 Answers1

1
def digitsndots(text):                                          
    if text in ["1","2","3","4","5","6","7","8","9","0","."]:   
        return True                                             
    else:                                                       
        return False                                            
num = float(filter(digitsndots, "36.12minuts"))
print num

When using this make sure your string does not have digits in between like "1.a.34.c" (courtesy of @Taha)

Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
  • 1
    The idea isn't bad, but one should be careful because it can misbehave. For example: `num("36.12minuts84") = num("36.1284") = 36.1284` and `num("36.12.84minuts") = num("36.12.84")` raises an exception. It will be a work to take all these cases into consideration. There must be a more simple way. – Taha Jul 17 '14 at 11:51
  • It may work if we use an algorithm that splits the string on the first non numeric character or the second decimal character. This can be done, but I think there are more sophisticated ways. – Taha Jul 17 '14 at 11:57