Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Converting Strings To Numbers (http://www.programmingforums.org/showthread.php?t=1091)

Ooble Nov 10th, 2004 9:12 AM

I wrote a Python function a little while back that converts strings to numbers, for an app I was developing (which is currently on hold). It simply pulls out all the crap that isn't a number - for example, "8v52.x3" will become 852.3. It allows you to specify the return type - string, long integer or floating-point. Take a look:

:

def str2num (str, retType = ""):
  decimal = 0
  x = 0
 
  while x < len(str):
    if (not(str[x].isdigit() or str[x] == ".") or ((str[x] == ".") and decimal)):
      str = str[:x] + str[x+1:]
    elif str[x] == "." and not(decimal):
      decimal = 1
      x = x + 1
    else:
      x = x + 1
 
  if len(str) > 0:
    if str[0] == ".":
      str = "0" + str[:]
    if str[-1] == ".":
      str = str[:-1]
      decimal = 0
 
  if len(str) == 0:
    str = "0"
   
  if (retType == "string") or (retType == "str"):
    return str
  else:
    if retType == "float":
      return float(str)
    elif (retType == "int") or (retType == "integer"):
      return long(str)
    else:
      if decimal:
        return float(str)
      else:
        return long(str)


thechristelegacy Nov 10th, 2004 4:44 PM

looks good, I'll have to check it out ;)

JoeUser Dec 13th, 2004 11:28 PM

Actually, Thanks! I was just looking for something to change strings to ints. It works like a charm! Now you can have the satisfaction of knowing somebody actually used your code for something! How often does that happen!?! (if you're not a pro-programmer, not often ^_^ )

Ooble Dec 14th, 2004 3:50 AM

Heh. It's nice to know.

Beegie_B Dec 15th, 2004 9:59 PM

Solid and Simple Code Mate!

That is often quite useful, I made a small scrip that converted an IP addir to a simple int for my IP scanner, was almost the same code as your's

Beeg

Ooble Dec 16th, 2004 5:19 AM

Heh. 'Twould be slightly different - different purposes, different code. Glad to hear it looks clean though.


All times are GMT -5. The time now is 8:08 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC