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
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")
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.")
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).
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)
.
Checking if a string contains an int
int.ParseInt
will pass only when name
is an int
, and has no other characters.
You can check if a string contains a number anywhere in it with LINQ using Any
:
if (name.Any(Char.IsDigit)) {
...
}
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 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 can I check if a string represents an int, without using try/except?
If you're really just annoyed at using try/except
s all over the place, please just write a helper function:
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False
It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.
Related Topics
Pretty Urls Without Mod_Rewrite, Without .Htaccess
How to Redirect to Different Url Based on Roles in Symfony 2
How to Use PHPunit to Test a Function If That Function Is Supposed to Kill PHP
Bulk Rename Files in a Folder - PHP
One Form with Two Submit Buttons and Different Actions for Each Button
$_File Upload Large File Gives Error 1 Even Though Upload_Max_Size Is Bigger Than the File Size
Troubleshooting "The Use Statement with Non-Compound Name ... Has No Effect"
Mysql_Connect VS MySQL_Pconnect
Most Efficient Way to Get Next Letter in the Alphabet Using PHP
What Is Difference of Developing a Website in MVC and 3-Tier or N-Tier Architecture
Difference Between Set_Time_Limit() and Ini_Set('Max_Execution_Time', ...)
Detect Mobile Devices - and Tablet Devices
Error Checking for Pdo Prepared Statements
How to See the Actual Xml Generated by PHP Soap Client Class