﻿ Python: Parse a string to Float or Integer - w3resource # Python: Parse a string to Float or Integer

## Python Basic: Exercise-48 with Solution

Write a Python program to parse a string to Float or Integer.

Sample Solution-1:

Python Code:

``````n = "246.2458"
print(float(n))
print(int(float(n)))
```
```

Sample Output:

```246.2458
246
```

## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Sample Solution-2:

Python Code:

``````def test(s):
try:
return int(s)
except ValueError:
return float(s)
print(test('12'))
print(test('233.12'))
```
```

Sample Output:

```12
233.12
```

## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

Try-catch-else construct:

```try:
foo()
except Exception:
print("Exception occured")
else:
print("Exception didnt occur")
finally:
print("Always gets here")
```