📌  相关文章
📜  Python|检查给定的字符串是否为数字

📅  最后修改于: 2022-05-13 01:54:46.853000             🧑  作者: Mango

Python|检查给定的字符串是否为数字

给定一个字符串,编写一个Python程序来检查该字符串是否为数字。
例子:

Input:  28
Output: digit

Input: a
Output: not a digit. 

Input: 21ab
Output: not a digit. 


代码 #1:使用Python正则表达式
re.search() :此方法要么返回 None (如果模式不匹配),要么返回一个 re.MatchObject ,其中包含有关字符串匹配部分的信息。此方法在第一次匹配后停止,因此它最适合测试正则表达式而不是提取数据。

Python3
# Python program to identify the Digit
 
# import re module
 
# re module provides support
# for regular expressions
import re
 
# Make a regular expression
# for identifying a digit
regex = '^[0-9]+$'
     
# Define a function for
# identifying a Digit
def check(string):
 
     # pass the regular expression
     # and the string in search() method
    if(re.search(regex, string)):
        print("Digit")
         
    else:
        print("Not a Digit")
     
 
# Driver Code
if __name__ == '__main__' :
     
    # Enter the string
    string = "28"
     
    # calling run function
    check(string)
 
    string = "a"
    check(string)
 
    string = "21ab"
    check(string)
 
    string = "12ab12"
    check(string)


Python3
# Python code to check if string is numeric or not
     
# checking for numeric characters
string = '123ayu456'
print(string.isnumeric())
    
string = '123456'
print(string.isnumeric())


输出:
Digit
Not a Digit
Not a Digit
Not a Digit


代码 #2:使用字符串.isnumeric()函数

Python3

# Python code to check if string is numeric or not
     
# checking for numeric characters
string = '123ayu456'
print(string.isnumeric())
    
string = '123456'
print(string.isnumeric())
输出:
False
True