IT

문자열에 숫자가 포함되어 있는지 확인

lottoking 2020. 6. 9. 07:49
반응형

문자열에 숫자가 포함되어 있는지 확인


내가 찾은 대부분의 질문은 숫자로 된 문자를 찾고 있다는 사실에 편향되어있는 반면, 나는 숫자없는 문자열이되고 싶은 숫자를 찾고 있습니다. 문자열을 입력하고 숫자가 포함되어 있는지 확인하고 거부하는지 확인해야합니다.

이 함수 isdigit()True모든 문자가 숫자 인 경우 에만 반환 합니다. 사용자가 숫자를 입력했는지 확인하고 싶기 때문에 "1 개를 소유하고 있습니다"와 같은 문장이 있습니다.

어떤 아이디어?


당신은 사용할 수 있습니다 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

또는 다음과 같이 정규식을 사용할 수 있습니다

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

any의 조합을 사용할 수 있습니다 str.isdigit.

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

True문자열에 숫자가 있으면 함수가 반환 하고 그렇지 않으면를 반환 False합니다.

데모:

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

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

정규식을 더 잘 사용해야합니다. 훨씬 빠릅니다.

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

사용하다

str.isalpha () 

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

문자열의 모든 문자가 알파벳이고 하나 이상의 문자가 있으면 true를, 그렇지 않으면 false를 반환합니다.


문자열의 모든 문자에 isdigit () 함수를 적용 할 수 있습니다. 또는 정규식을 사용할 수 있습니다.

또한 파이썬에서 문자열에서 하나의 숫자를 어떻게 찾습니까? 숫자를 반환하는 매우 적합한 방법으로. 아래의 해결책은 그 질문에 대한 답변입니다.

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

또는

number = filter(str.isdigit, yourString)

자세한 내용은 정규식 문서를 참조하십시오 : 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.

The second method does not work.

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

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

You can use NLTK method for it.

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

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.')

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

You can accomplish this as follows:

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

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).


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

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

I'm surprised that no-one mentionned this combination of any and map:

def contains_digit(s):
    isdigit = str.isdigit
    return any(map(isdigit,s))

in python 3 it's probably the fastest there (except maybe for regexes) is because it doesn't contain any loop (and aliasing the function avoids looking it up in str).

Don't use that in python 2 as map returns a list, which breaks any short-circuiting


import string
import random
n = 10

p = ''

while (string.ascii_uppercase not in p) and (string.ascii_lowercase not in p) and (string.digits not in p):
    for _ in range(n):
        state = random.randint(0, 2)
        if state == 0:
            p = p + chr(random.randint(97, 122))
        elif state == 1:
            p = p + chr(random.randint(65, 90))
        else:
            p = p + str(random.randint(0, 9))
    break
print(p)

This code generates a sequence with size n which at least contain an uppercase, lowercase, and a digit. By using the while loop, we have guaranteed this event.


any and ord can be combined to serve the purpose as shown below.

>>> def hasDigits(s):
...     return any( 48 <= ord(char) <= 57 for char in s)
...
>>> hasDigits('as1')
True
>>> hasDigits('as')
False
>>> hasDigits('as9')
True
>>> hasDigits('as_')
False
>>> hasDigits('1as')
True
>>>

A couple of points about this implementation.

  1. any is better because it works like short circuit expression in C Language and will return result as soon as it can be determined i.e. in case of string 'a1bbbbbbc' 'b's and 'c's won't even be compared.

  2. ord is better because it provides more flexibility like check numbers only between '0' and '5' or any other range. For example if you were to write a validator for Hexadecimal representation of numbers you would want string to have alphabets in the range 'A' to 'F' only.

참고URL : https://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number

반응형