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 map()
Python String isalnum()
Java – Generate Random String
Python Shallow Copy and Deep Copy
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python memoryview()
Java InputStream to String
Python Program to Print the Fibonacci sequence
Python time Module
Python Program to Slice Lists
Python Operator Overloading
Python hash()
Python Program to Find the Factorial of a Number
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Create a Countdown Timer
Python Data Structures and Algorithms - Benjamin Baka
Python Package
Python Program to Print all Prime Numbers in an Interval
Converting String to Stream of chars
Python slice()
Python max()
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Find HCF or GCD
Python dir()
Python vars()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python datetime
Python Anonymous / Lambda Function
Java – Reader to String
Python Program to Check Whether a String is Palindrome or Not
Python String format_map()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...