1. 首页 > 快讯

判断字符串是否为数字python(c++判断是否是数字)

如何判断一串数字符合指定格式?

您需要判断一组数字是否符合以下格式:

  • 最少包含 6 位,最多包含 7 位
  • 用空格分隔
  • 只能包含数字或 '*'

解决方案:

可以使用 Python 中的正则表达式来轻松判断:

import re

def check_format(input_string):
    # 正则表达式匹配 6 或 7 个由空格分隔的数字或星号
    pattern = r'^(d|*)+(s(d|*)+){5,6}$'
    match = re.fullmatch(pattern, input_string)
    return match is not None
登录后复制

示例:

以下代码示例展示了如何使用该函数:

input_a = "1 2 3 4 5 6"
input_b = "* 2 3 4 5 6"
input_c = "1 2 3 4 5 6 7"

print(check_format(input_a))  # True
print(check_format(input_b))  # True
print(check_format(input_c))  # False
登录后复制

本文采摘于网络,不代表本站立场,转载联系作者并注明出处:https://www.iotsj.com//kuaixun/6883.html

联系我们

在线咨询:点击这里给我发消息

微信号:666666