检查字符串是否包含数字

时间:2022-09-08 01:44:26

Most of the questions I've found are biased on the fact they're looking for letters in their numbers, whereas I'm looking for numbers in what I'd like to be a numberless string. I need to enter a string and check to see if it contains any numbers and if it does reject it.

我发现的大多数问题都是因为他们正在寻找他们的数字中的字母,而我正在寻找我希望成为无数字符串的数字。我需要输入一个字符串并检查它是否包含任何数字,如果它确实拒绝它。

the function isdigit() only returns true if ALL of the characters are numbers. I just want to see if the user has entered a number so a sentence like "I own 1 dog" or something.

如果所有字符都是数字,则函数isdigit()仅返回true。我只是想看看用户是否输入了一个数字,如“我拥有1只狗”之类的句子。

Any ideas?

有任何想法吗?

10 个解决方案

#1


146  

You can use any function, with the str.isdigit function, like this

你可以使用任何函数,使用str.isdigit函数,就像这样

>>> def hasNumbers(inputString):
...     return any(char.isdigit() for char in inputString)
... 
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False

Alternatively you can use a Regular Expression, like this

或者,您可以使用正则表达式,如下所示

>>> import re
>>> def hasNumbers(inputString):
...     return bool(re.search(r'\d', inputString))
... 
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False

#2


27  

You can use a combination of any and str.isdigit:

您可以使用any和str.isdigit的组合:

def num_there(s):
    return any(i.isdigit() for i in s)

The function will return True if a digit exists in the string, otherwise False.

如果字符串中存在数字,则该函数将返回True,否则返回False。

Demo:

演示:

>>> king = 'I shall have 3 cakes'
>>> num_there(king)
True
>>> servant = 'I do not have any cakes'
>>> num_there(servant)
False

#3


21  

https://docs.python.org/2/library/re.html

https://docs.python.org/2/library/re.html

You should better use regular expression. It's much faster.

你应该更好地使用正则表达式。它要快得多。

import re

def f1(string):
    return any(i.isdigit() for i in string)


def f2(string):
    return re.search('\d', string)


# if you compile the regex string first, it's even faster
RE_D = re.compile('\d')
def f3(string):
    return RE_D.search(string)

# Output from iPython
# In [18]: %timeit  f1('assdfgag123')
# 1000000 loops, best of 3: 1.18 µs per loop

# In [19]: %timeit  f2('assdfgag123')
# 1000000 loops, best of 3: 923 ns per loop

# In [20]: %timeit  f3('assdfgag123')
# 1000000 loops, best of 3: 384 ns per loop

#4


13  

use

使用

str.isalpha() 

Ref: https://docs.python.org/2/library/stdtypes.html#str.isalpha

参考:https://docs.python.org/2/library/stdtypes.html#str.isalpha

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

如果字符串中的所有字符都是字母并且至少有一个字符,则返回true,否则返回false。

#5


6  

You could apply the function isdigit() on every character in the String. Or you could use regular expressions.

您可以对String中的每个字符应用函数isdigit()。或者你可以使用正则表达式。

Also I found How do I find one number in a string in Python? with very suitable ways to return numbers. The solution below is from the answer in that question.

另外我发现如何在Python中的字符串中找到一个数字?以非常合适的方式返回数字。以下解决方案来自该问题的答案。

number = re.search(r'\d+', yourString).group()

Alternatively:

或者:

number = filter(str.isdigit, yourString)

For further Information take a look at the regex docu: http://docs.python.org/2/library/re.html

有关详细信息,请查看正则表达式文档:http://docs.python.org/2/library/re.html

Edit: This Returns the actual numbers, not a boolean value, so the answers above are more correct for your case

编辑:返回实际数字,而不是布尔值,因此上面的答案对于您的情况更正确

The first method will return the first digit and subsequent consecutive digits. Thus 1.56 will be returned as 1. 10,000 will be returned as 10. 0207-100-1000 will be returned as 0207.

第一种方法将返回第一个数字和后续连续数字。因此,1.56将返回1. 10,000将返回10. 0207-100-1000将返回0207。

The second method does not work.

第二种方法不起作用。

To extract all digits, dots and commas, and not lose non-consecutive digits, use:

要提取所有数字,点和逗号,而不是丢失非连续数字,请使用:

re.sub('[^\d.,]' , '', yourString)

re.sub('[^ \ d。,]','',yourString)

#6


1  

What about this one?

这个如何?

import string

def containsNumber(line):
    res = False
    try:
        for val in line.split():
            if (float(val.strip(string.punctuation))):
                res = True
                break
    except ValueError, e:
        pass
    return res

print containsNumber('234.12 a22') # returns True
print containsNumber('234.12L a22') # returns False
print containsNumber('234.12, a22') # returns True

#7


1  

You can accomplish this as follows:

您可以按如下方式完成此操作:

if a_string.isdigit(): do_this() else: do_that()

如果a_string.isdigit():do_this()else:do_that()

https://docs.python.org/2/library/stdtypes.html#str.isdigit

https://docs.python.org/2/library/stdtypes.html#str.isdigit

Using .isdigit() also means not having to resort to exception handling (try/except) in cases where you need to use list comprehension (try/except is not possible inside a list comprehension).

使用.isdigit()也意味着在需要使用列表理解的情况下不必诉诸异常处理(try / except)(在列表解析中不可能尝试/ except)。

#8


1  

You can use NLTK method for it.

您可以使用NLTK方法。

This will find both '1' and 'One' in the text:

这将在文本中找到'1'和'One':

import nltk 

def existence_of_numeric_data(text):
    text=nltk.word_tokenize(text)
    pos = nltk.pos_tag(text)
    count = 0
    for i in range(len(pos)):
        word , pos_tag = pos[i]
        if pos_tag == 'CD':
            return True
    return False

existence_of_numeric_data('We are going out. Just five you and me.')

#9


1  

You can use range with count to check how many times a number appears in the string by checking it against the range:

您可以使用带有计数的范围来检查数字在字符串中出现的次数,方法是在范围内进行检查:

def count_digit(a):
    sum = 0
    for i in range(10):
        sum += a.count(str(i))
    return sum

ans = count_digit("apple3rh5")
print(ans)

#This print 2

#10


0  

Simpler way to solve is as

更简单的解决方法是

s = '1dfss3sw235fsf7s'
count = 0
temp = list(s)
for item in temp:
    if(item.isdigit()):
        count = count + 1
    else:
        pass
print count

#1


146  

You can use any function, with the str.isdigit function, like this

你可以使用任何函数,使用str.isdigit函数,就像这样

>>> def hasNumbers(inputString):
...     return any(char.isdigit() for char in inputString)
... 
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False

Alternatively you can use a Regular Expression, like this

或者,您可以使用正则表达式,如下所示

>>> import re
>>> def hasNumbers(inputString):
...     return bool(re.search(r'\d', inputString))
... 
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False

#2


27  

You can use a combination of any and str.isdigit:

您可以使用any和str.isdigit的组合:

def num_there(s):
    return any(i.isdigit() for i in s)

The function will return True if a digit exists in the string, otherwise False.

如果字符串中存在数字,则该函数将返回True,否则返回False。

Demo:

演示:

>>> king = 'I shall have 3 cakes'
>>> num_there(king)
True
>>> servant = 'I do not have any cakes'
>>> num_there(servant)
False

#3


21  

https://docs.python.org/2/library/re.html

https://docs.python.org/2/library/re.html

You should better use regular expression. It's much faster.

你应该更好地使用正则表达式。它要快得多。

import re

def f1(string):
    return any(i.isdigit() for i in string)


def f2(string):
    return re.search('\d', string)


# if you compile the regex string first, it's even faster
RE_D = re.compile('\d')
def f3(string):
    return RE_D.search(string)

# Output from iPython
# In [18]: %timeit  f1('assdfgag123')
# 1000000 loops, best of 3: 1.18 µs per loop

# In [19]: %timeit  f2('assdfgag123')
# 1000000 loops, best of 3: 923 ns per loop

# In [20]: %timeit  f3('assdfgag123')
# 1000000 loops, best of 3: 384 ns per loop

#4


13  

use

使用

str.isalpha() 

Ref: https://docs.python.org/2/library/stdtypes.html#str.isalpha

参考:https://docs.python.org/2/library/stdtypes.html#str.isalpha

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

如果字符串中的所有字符都是字母并且至少有一个字符,则返回true,否则返回false。

#5


6  

You could apply the function isdigit() on every character in the String. Or you could use regular expressions.

您可以对String中的每个字符应用函数isdigit()。或者你可以使用正则表达式。

Also I found How do I find one number in a string in Python? with very suitable ways to return numbers. The solution below is from the answer in that question.

另外我发现如何在Python中的字符串中找到一个数字?以非常合适的方式返回数字。以下解决方案来自该问题的答案。

number = re.search(r'\d+', yourString).group()

Alternatively:

或者:

number = filter(str.isdigit, yourString)

For further Information take a look at the regex docu: http://docs.python.org/2/library/re.html

有关详细信息,请查看正则表达式文档:http://docs.python.org/2/library/re.html

Edit: This Returns the actual numbers, not a boolean value, so the answers above are more correct for your case

编辑:返回实际数字,而不是布尔值,因此上面的答案对于您的情况更正确

The first method will return the first digit and subsequent consecutive digits. Thus 1.56 will be returned as 1. 10,000 will be returned as 10. 0207-100-1000 will be returned as 0207.

第一种方法将返回第一个数字和后续连续数字。因此,1.56将返回1. 10,000将返回10. 0207-100-1000将返回0207。

The second method does not work.

第二种方法不起作用。

To extract all digits, dots and commas, and not lose non-consecutive digits, use:

要提取所有数字,点和逗号,而不是丢失非连续数字,请使用:

re.sub('[^\d.,]' , '', yourString)

re.sub('[^ \ d。,]','',yourString)

#6


1  

What about this one?

这个如何?

import string

def containsNumber(line):
    res = False
    try:
        for val in line.split():
            if (float(val.strip(string.punctuation))):
                res = True
                break
    except ValueError, e:
        pass
    return res

print containsNumber('234.12 a22') # returns True
print containsNumber('234.12L a22') # returns False
print containsNumber('234.12, a22') # returns True

#7


1  

You can accomplish this as follows:

您可以按如下方式完成此操作:

if a_string.isdigit(): do_this() else: do_that()

如果a_string.isdigit():do_this()else:do_that()

https://docs.python.org/2/library/stdtypes.html#str.isdigit

https://docs.python.org/2/library/stdtypes.html#str.isdigit

Using .isdigit() also means not having to resort to exception handling (try/except) in cases where you need to use list comprehension (try/except is not possible inside a list comprehension).

使用.isdigit()也意味着在需要使用列表理解的情况下不必诉诸异常处理(try / except)(在列表解析中不可能尝试/ except)。

#8


1  

You can use NLTK method for it.

您可以使用NLTK方法。

This will find both '1' and 'One' in the text:

这将在文本中找到'1'和'One':

import nltk 

def existence_of_numeric_data(text):
    text=nltk.word_tokenize(text)
    pos = nltk.pos_tag(text)
    count = 0
    for i in range(len(pos)):
        word , pos_tag = pos[i]
        if pos_tag == 'CD':
            return True
    return False

existence_of_numeric_data('We are going out. Just five you and me.')

#9


1  

You can use range with count to check how many times a number appears in the string by checking it against the range:

您可以使用带有计数的范围来检查数字在字符串中出现的次数,方法是在范围内进行检查:

def count_digit(a):
    sum = 0
    for i in range(10):
        sum += a.count(str(i))
    return sum

ans = count_digit("apple3rh5")
print(ans)

#This print 2

#10


0  

Simpler way to solve is as

更简单的解决方法是

s = '1dfss3sw235fsf7s'
count = 0
temp = list(s)
for item in temp:
    if(item.isdigit()):
        count = count + 1
    else:
        pass
print count