string to numeric conversion

Posted on 2005-05-10
Medium Priority
Last Modified: 2010-04-16
I have a string "70%"

but i need to convert it to decimal, so I can compare it against different level?

How can thos conversion be perfomed?
Question by:RobertoDeAlba
LVL 14

Accepted Solution

RichieHindle earned 400 total points
ID: 13976225
First get just the numeric part of the string:

STR = "70%"
import re
match = re.match("([0-9]+)", STR)

then convert the numeric part of the string to an integer:

value = int(match.group(1))

'value' is now 70 (an integer).

If you can have fractions (eg. "70.5%") then you need to match the decimal point as well as the digits, and convert to a float:

STR = "70.5%"
import re
match = re.match("([0-9.]+)", STR)
value = float(match.group(1))

'value' is now 70.5 (a float).

Author Comment

ID: 13978955
Thanks, thatis exactly what I needed

Best Regards

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses
Course of the Month16 days, 12 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question