Solved

# string to numeric conversion

Posted on 2005-05-10
Medium Priority
338 Views
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?
0
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).
0

Author Comment

ID: 13978955
Thanks, thatis exactly what I needed

Best Regards
0

## Featured Post

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