Como verificar uma string contém um número em Python
-
Python
any
Função comstr.isdigit
para verificar se uma String contém um número -
Função
map()
-
re.search(r'\d')
para verificar se uma string contém um número

Este artigo introduz como verificar se uma string Python contém um número ou não.
Python embutido any
função junto com str.isdigit
retornará True
se a string dada contiver um número, caso contrário, retornará False
.
O método de busca de expressão regular Python com padrão r'\d'
pode também retornar True
se a string dada contiver um número.
Python any
Função com str.isdigit
para verificar se uma String contém um número
any
função retorna True
se qualquer elemento da função iterable
for True
, caso contrário, retorna False
.
str.isdigit()
retorna True
se todos os caracteres da string dada forem dígitos, False
de outra forma.
any(chr.isdigit() for chr in stringExample)
Se stringExample
contém pelo menos um número, então o código acima retorna True
porque chr.isdigit() for chr in stringExample)
para chr na stringExample
tem pelo menos um True
na iterable
.
Exemplo de trabalho*
str1 = "python1"
str2 = "nonumber"
str3 = "12345"
print(any(chr.isdigit() for chr in str1))
print(any(chr.isdigit() for chr in str2))
print(any(chr.isdigit() for chr in str3))
Resultado:
True
False
True
Função map()
Python map(function, iterable)
função aplica function
a cada elemento do dado iterable
e retorna um iterador que produz o resultado acima.
Portanto, poderíamos reescrever a solução acima para,
any(map(str.isdigit, stringExample))
Exemplo de trabalho
str1 = "python1"
str2 = "nonumber"
str3 = "12345"
print(any(map(str.isdigit, str1)))
print(any(map(str.isdigit, str2)))
print(any(map(str.isdigit, str3)))
Resultado:
True
False
True
re.search(r'\d')
para verificar se uma string contém um número
re.search(r'\d', string)
padrão escaneia a string
e retorna o objeto que corresponde ao primeiro local que corresponde ao padrãofornecido - \d
que significa qualquer número entre 0 e 9 e retorna None
se não for encontrada nenhuma correspondência.
import re
print(re.search(r"\d", "python3.8"))
# output: <re.Match object; span=(6, 7), match='3'>
O objeto correspondente contém o span
de 2 tubos que indica a posição inicial e final do match
, e também o conteúdo correspondente como match = '3'
.
A função bool()
pode lançar o resultado de re.search
do objeto match
ou None
para True
ou False
.
Exemplo de trabalho
import re
str1 = "python12"
str2 = "nonumber"
str3 = "12345"
print(bool(re.search(r"\d", str1)))
print(bool(re.search(r"\d", str2)))
print(bool(re.search(r"\d", str3)))
Resultado:
True
False
True
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook