Check if a string contains a number
You can use any
function, with the str.isdigit
function, like this
def has_numbers(inputString):
return any(char.isdigit() for char in inputString)
has_numbers("I own 1 dog")
# True
has_numbers("I own no dog")
# False
Alternatively you can use a Regular Expression, like this
import re
def has_numbers(inputString):
return bool(re.search(r'\d', inputString))
has_numbers("I own 1 dog")
# True
has_numbers("I own no dog")
# False
Check and extract a number from a String in Java
The solution I went with looks like this:
Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);
Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);
if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}
I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)
check if string contains an integer python
Your code works fine if you unindent the else
to make it part of the for
:
for num in password:
if num.isdigit():
break
else:
print("Your password must contain a number.")
If it's part of the if
, the else
happens for every character that's not a digit; if it's part of the for
, it happens at the end of the loop if the loop was never broken, which is the behavior you want.
An easier way of writing the same check is with the any
function ("if there aren't any digits..."):
if not any(num.isdigit() for num in password):
print("Your password must contain a number.")
or equivalently with all
("if all the characters aren't digits..."):
if all(not num.isdigit() for num in password):
print("Your password must contain a number.")
Java String - See if a string contains only numbers and not letters
If you'll be processing the number as text, then change:
if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
to:
if (text.matches("[0-9]+") && text.length() > 2) {
Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.
If you actually want to use the numeric value, use Integer.parseInt()
or Double.parseDouble()
as others have explained below.
As a side note, it's generally considered bad practice to compare boolean values to true
or false
. Just use if (condition)
or if (!condition)
.
How to check if a string contains a number in powershell
Use a regular expression match:
'paul123' -match '\d'
\d
matches a digit (0-9), so the expression will evaluate to true if the string contains at least one digit.
check if string contains number and return the number
List Comprehension
: Return the digitsTo return the digits, use a list comprehension with
if
def hashnumbers(inputString):
return [char for char in inputString if char.isdigit()]
print(hashnumbers("super string")) # []
print(hashnumbers("super 2 string")) # ['2']
print(hashnumbers("super 2 3 string")) # ['2', '3']Return a default value if no digits found (empty list is evaluated as False)
return [char for char in inputString if char.isdigit()] or None
Regex version with
re.findall
return re.findall(r"\d", inputString)
return re.findall(r"\d", inputString) or NoneReturn first one only
def hashnumbers(inputString):
return next((char for char in inputString if char.isdigit()), None)
print(hashnumbers("super string")) # None
print(hashnumbers("super 2 string")) # 2
print(hashnumbers("super 2 3string")) # 2
How to determine whether a string contains an integer?
If you want to make sure that it is only an integer and convert it to one, I would use parseInt in a try/catch
. However, if you want to check if the string contains a number then you would be better to use the String.matches with Regular Expressions: stringVariable.matches("\\d")
In C#, how to check whether a string contains an integer?
The answer seems to be just no.
Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).
Related Topics
Accessing Dict Keys Like an Attribute
Pandas Read_SQL With Parameters
Ignore Case in Glob() on Linux
Auto.Arima() Equivalent for Python
Gae " No Attribute 'Httpshandler' " Dev_Appserver.Py
Binding Callbacks to Minimize and Maximize Events in Toplevel Windows
Pyodbc:Can't Open the Driver Even If It Exists
Python Multiprocessing - Debugging Oserror: [Errno 12] Cannot Allocate Memory
Python Program with Notification in Gnome Shell Doesn't Work
Faster Way to Find Large Files with Python
Convert Utc Datetime String to Local Datetime
How to Base-64 Encode a Png Image for Use in a Data-Uri in a CSS File
Python Multiprocessing Memory Usage
What Are Python Pandas Equivalents for R Functions Like Str(), Summary(), and Head()
How to Make the Python Program to Check Linux Services
Why Not Just Use 'Shell=True' in Subprocess.Popen in Python
Package Libffi Was Not Found in the Pkg-Config Search Path Redhat6.5
How to Make Shell Output Redirect (>) Write While Script Is Still Running