Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check string for numbers in Python

How to check if string contains numbers in Python?

I have a variable which I am convert to float, but I want to make if statement, to convert it to float only if it contains only numbers.

like image 793
Marko Avatar asked Aug 04 '11 13:08

Marko


People also ask

How do you check if there are numbers in a string Python?

Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

How do you check if a string contains letters and numbers in Python?

isalnum() is a built-in Python function that checks whether all characters in a string are alphanumeric. In other words, isalnum() checks whether a string contains only letters or numbers or both. If all characters are alphanumeric, isalnum() returns the value True ; otherwise, the method returns the value False .


1 Answers

Just convert it and catch the exception if it fails.

s = "3.14"
try:
  val = float(s)
except ValueError:
  val = None
like image 125
Michael J. Barber Avatar answered Sep 28 '22 09:09

Michael J. Barber