![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 8
![]() |
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) |
|
|
|
|
|
#2 |
|
Expert Programmer
|
looks good, I'll have to check it out
![]() |
|
|
|
|
|
#3 |
|
Newbie
Join Date: Dec 2004
Posts: 8
Rep Power: 0
![]() |
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 ^_^ )
|
|
|
|
|
|
#4 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 8
![]() |
Heh. It's nice to know.
|
|
|
|
|
|
#5 |
|
Programmer
|
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 |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|