查找字符串是否没有整数

2024-10-01 00:31:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有密码:

user_input = input('>>>: ')
if not re.search('[0-9]', user_input):
    print('That wasn\'t an integer.')
else:
    print('That was an integer!')
    print(user_input)

它基本上试图确定用户的输入(数学上)是否是整数。如果输入为“adgx”,则此操作有效;代码识别出这些值不在0-9范围内,并且print的值不是整数。我需要程序打印'这不是一个整数'。如果输入是例如'a3h1d',但它没有。我假设,因为从技术上讲,输入包含的数字在范围内,所以它满足了语句的要求。我需要它,这样如果输入是'a3h1d',程序就会打印'那不是整数'


Tags: 程序rean密码inputsearchifthat
2条回答

也可以使用re.match()加上字符串开头和字符串结尾标记:

user_input = input('>>>: ')
if not re.match('^[0-9]+$', user_input):
    print('That wasn\'t an integer.')
else:
    print('That was an integer!')

记住,在正则表达式中:

  • ^匹配行的开头
  • $匹配行尾
  • +表示前面的模式应该出现一次或多次

我建议看一下Python official 're' documentation以获得一个更完整、解释更清楚的列表

如果您不想使用正则表达式,我建议您只使用^{}

user_input = input('>>>: ')
if not user_input.isdigit():
    print('That wasn\'t an integer.')
else:
    print('That was an integer!')

还有一种方法

try:
    user_input = int(input('>>>: '))
    print('That was an integer!')
except ValueError:
    print('That wasn\'t an integer.')

相关问题 更多 >