Home » Python

How do I check if a string is a number (float) in Python?

Example of float() method: Here, we are going to learn how do I check if a string is a number (float) in Python?
Submitted by Sapna Deraje Radhakrishna, on November 24, 2019

Using python it is very to interconvert the datatypes of a variable. A string can be easily converted to an integer or a float. However, asserting a string to be a float is a task by itself. Python provides an option to assert if a string is a float.

float()

Using the float() method, a variable can be type casted to a float variable. However, if the variable is not a valid float an exception is thrown.

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_string = "45.02"
>>> print("The original string is {}".format(test_string))
The original string is 45.02
>>> try:
...     float(test_string)
...     print("{} is a valid float variable".format(test_string))
... except:
...     print("invalid float variable")
...
45.02
45.02 is a valid float variable
>>> test_string = "aa"
>>> try:
...     float(test_string)
...     print("{} is a valid float variable".format(test_string))
... except:
...     print("invalid float variable")
...
invalid float variable






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.