欢迎访问宙启技术站
智能推送

使用Python函数判断输入的字符串是否为数字类型

发布时间:2023-11-05 10:21:36

方法一:使用内置函数isdigit()

isdigit()是字符串内置的方法,用于判断字符串是否只包含数字字符。它返回True表示字符串只包含数字字符,否则返回False。因此,我们可以通过调用该方法来判断输入的字符串是否为数字类型。

def is_numeric(input_str):
    return input_str.isdigit()

# 示例调用
str1 = "1234"
str2 = "abc123"
print(is_numeric(str1))  # True
print(is_numeric(str2))  # False

方法二:使用正则表达式

通过使用正则表达式可以更灵活地判断字符串是否为数字类型。使用正则表达式模式"[0-9]+"来匹配至少一个数字字符。可以使用re模块中的match()函数来匹配字符串与模式。

import re

def is_numeric(input_str):
    pattern = re.compile("[0-9]+")
    return pattern.match(input_str) is not None

# 示例调用
str1 = "1234"
str2 = "abc123"
print(is_numeric(str1))  # True
print(is_numeric(str2))  # False

以上是两种常见的判断字符串是否为数字类型的方法。需要区分的是,isdigit()方法只能判断整数类型的字符串,无法处理带有小数部分或其他特殊字符的字符串。而正则表达式则可以根据需要进行灵活的匹配和判断。