Table of Contents
In this example, you will learn to parse a string to a float or int.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Parse string into integer
balance_str = "1500" balance_int = int(balance_str) # print the type print(type(balance_int)) # print the value print(balance_int)
Output
<class 'int'> 1500
int()
can be used to parse a string to an integer. The argument passed balance_int
is the string. As shown in the above example, you can see the type of the string changed to int
.
Note: The string must be a numeral value.
2. Example 2: Parse string into float
balance_str = "1500.4" balance_float = float(balance_str) # print the type print(type(balance_float)) # print the value print(balance_float)
Output
<class 'float'> 1500.4
float()
can be used to parse a string to an integer. Similar to Example 1, the string is passed as an argument to float()
.
3. Example 3: A string float numeral into integer
balance_str = "1500.34" balance_int = int(float(balance_str)) # print the type print(type(balance_int)) # print the value print(balance_int)
Output
<class 'int'> 1500
If the string is a float numeral, you can convert it into a float type using float()
, and then parse it to an integer using int()
.
Related posts:
Python Program to Swap Two Variables
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python String strip()
Python Program to Shuffle Deck of Cards
Python Set pop()
Python type()
Python Program to Differentiate Between del, remove, and pop on a List
Python print()
Python Program to Convert Celsius To Fahrenheit
Python String islower()
Python List
Python sleep()
Deep Learning with Python - Francois Chollet
Python String rindex()
Python List reverse()
Python Set copy()
Converting a List to String in Java
APIs in Node.js vs Python - A Comparison
Python dict()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Machine Learning - Sebastian Raschka
Python Program to Get File Creation and Modification Date
Python List Comprehension
Python bool()
Python round()
Python int()
Python strptime()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Create a Countdown Timer
Python RegEx
Python Directory and Files Management
Python String lstrip()