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 Compute the Power of a Number
Check if a String is a Palindrome in Java
String Hashing
Python Shallow Copy and Deep Copy
String Initialization in Java
Python Program to Create Pyramid Patterns
Java Program to Permute All Letters of an Input String
Python repr()
Python Set intersection()
Python Program to Shuffle Deck of Cards
Converting a Stack Trace to a String in Java
Python Set add()
Split a String in Java
Python String istitle()
Python String count()
Python Program to Get the Full Path of the Current Working Directory
Python Set remove()
Python String format_map()
Python String isprintable()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Sort Words in Alphabetic Order
Python bytearray()
Python Set issuperset()
Encode a String to UTF-8 in Java
Python Get Current time
Python String rpartition()
Python Exception Handling Using try, except and finally statement
Python Numbers, Type Conversion and Mathematics
Python round()
Python String ljust()
String Processing with Apache Commons Lang 3
CharSequence vs. String in Java