I am created a pythod method that will take in a string of variable length, that will always include a floating point number at the end :
"adsfasdflkdslf:asldfasf-adslfk:1.5698464586546"
OR
"asdif adfi=9393 adfkdsf:1.84938"
I need to parse the string and return the floating point number at the end. There usually a delimiter character before the float, such as : – or a space.
def findFloat(stringArg):
stringArg.rstrip()
stringArg.replace("-",":")
if stringArg.rfind(":"):
locateFloat = stringArg.rsplit(":")
#second element should be the desired float
magicFloat = locateFloat[1]
return magicFloat
I am recieving a
magicFloat = locateFloat[1]
IndexError: list index out of range
Any guidence on how to locate the float and return it would be awesome.
In Python, strings are immutable. No matter what function you call on a string, the actual text of that string does not change. Thus, methods like
rstrip,replaceetc. create a new string representing the modified version. (You would know this if you read the documentation.) In your code, you do not assign the results of these calls anywhere in the first two statements, so the results are lost.Without specifying a number of splits,
rsplitdoes the exact same thing thatsplitdoes. It checks for splits from the end, sure, but it still splits at every possible point, so the net effect is the same. You need to specify that you want to split at most one time.However, you shouldn’t do that anyway; a much simpler way to get “everything after the last colon, or everything if there is no colon” is to use
rpartition.You don’t actually have to remove whitespace from the end for
floatconversion. Although you probably should actually, you know, perform the conversion.Finally, there is no point in assigning to a variable just to return it; just return the expression directly.
Putting that together gives us the exceptionally simple: