Python 检查字符串是否包含数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19859282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a string contains a number
提问by JamesDonnelly
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
在所有字符都是数字时返回。我只是想看看用户是否输入了一个数字,比如一句话之类的"I own 1 dog"
。
Any ideas?
有任何想法吗?
采纳答案by thefourtheye
You can use any
function, with the str.isdigit
function, like this
你可以使用any
函数,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
回答by aIKid
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
回答by Haini
You could apply the function isdigit() on every character in the String. Or you could use regular expressions.
您可以对字符串中的每个字符应用函数 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)
回答by aga
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:
pass
return res
containsNumber('234.12 a22') # returns True
containsNumber('234.12L a22') # returns False
containsNumber('234.12, a22') # returns True
回答by K246
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。
回答by zyxue
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
回答by pedmindset
You can use range with count to check how many times a number appears in the string by checking it against the range:
您可以使用 range 和 count 来检查数字在字符串中出现的次数,方法是根据范围检查它:
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
回答by Mahendra S. Chouhan
You can use NLTK method for it.
您可以使用 NLTK 方法。
This will find both '1' and 'One' in the text:
这将在文本中找到“1”和“一”:
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.')
回答by olisteadman
You can accomplish this as follows:
您可以按如下方式完成此操作:
if a_string.isdigit():
do_this()
else:
do_that()
if 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()
也意味着在需要使用列表推导式的情况下不必求助于异常处理(尝试/除外)(在列表推导式中尝试/除外是不可能的)。
回答by BlizZard
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