Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么使用正则表达式检查用户的输入会在Python中显示错误消息?_Python_Regex - Fatal编程技术网

为什么使用正则表达式检查用户的输入会在Python中显示错误消息?

为什么使用正则表达式检查用户的输入会在Python中显示错误消息?,python,regex,Python,Regex,我是一个新的Python学习者。我写了下面的代码,用于一个程序,该程序读取一个数字(如1234),将所有数字相加(结果为10),并显示结果 如果我删除正则表达式部分,它就会工作。但是,我想知道为什么代码不能与它一起工作 import re numbers= int(input("Enter a number e.g. 1234 :")) n=re.match('(\d+)', number) if n: total = 0 for number in numbers:

我是一个新的Python学习者。我写了下面的代码,用于一个程序,该程序读取一个数字(如1234),将所有数字相加(结果为10),并显示结果

如果我删除正则表达式部分,它就会工作。但是,我想知道为什么代码不能与它一起工作

import re

numbers= int(input("Enter a number e.g. 1234 :"))
n=re.match('(\d+)', number)

if n:
    total = 0 
    for number in numbers: 
        total += number
        print ("The total sum is:",total)

else:
    print ("invalid input!")

谢谢大家!

re.match返回匹配实例:

>>> import re
>>> number='123'  # just an example
>>> re.match('(\d+)', number)
<_sre.SRE_Match object; span=(0, 3), match='123'>
正则表达式可能有用的一个例子是删除不需要的字符串。例如:

>>> number='123 kg'
>>> re.match('(\d+)', number).group()
'123'
要求和超过位数:

>>> number='123 kg'
>>> digits = re.match('(\d+)', number).group()
>>> sum(int(c) for c in digits)
6

re.match返回匹配实例:

>>> import re
>>> number='123'  # just an example
>>> re.match('(\d+)', number)
<_sre.SRE_Match object; span=(0, 3), match='123'>
正则表达式可能有用的一个例子是删除不需要的字符串。例如:

>>> number='123 kg'
>>> re.match('(\d+)', number).group()
'123'
要求和超过位数:

>>> number='123 kg'
>>> digits = re.match('(\d+)', number).group()
>>> sum(int(c) for c in digits)
6

正则表达式用于匹配和比较字符串。将输入转换为
int
regex时将失败,因为它不再与字符串进行比较

此外,不能对整数进行迭代。我认为您要做的是检查字符串输入是否都是数字,然后迭代字符串中的数字,将它们转换为整数,然后进行求和

试试这个:

import re

number= input("Enter a number of variable length e.g. 73618 :")
n=re.match('(\d+)', number)

if n:
    total = 0 
    for digit in number: 
        total += int(digit)
        print ("The total sum of digits is:",total)

else:
    print ("Error! Make sure you only use numbers")

正则表达式用于匹配和比较字符串。将输入转换为
int
regex时将失败,因为它不再与字符串进行比较

此外,不能对整数进行迭代。我认为您要做的是检查字符串输入是否都是数字,然后迭代字符串中的数字,将它们转换为整数,然后进行求和

试试这个:

import re

number= input("Enter a number of variable length e.g. 73618 :")
n=re.match('(\d+)', number)

if n:
    total = 0 
    for digit in number: 
        total += int(digit)
        print ("The total sum of digits is:",total)

else:
    print ("Error! Make sure you only use numbers")
根据python文档:

re.match(pattern, string, flags=0)
如果字符串开头的零个或多个字符与 正则表达式模式,返回相应的MatchObject 例如。如果字符串与模式不匹配,则返回None

因此,这里需要做的是检查regex返回的值是否不是
None

即,
如果n不是None:
根据python文档:

re.match(pattern, string, flags=0)
如果字符串开头的零个或多个字符与 正则表达式模式,返回相应的MatchObject 例如。如果字符串与模式不匹配,则返回None

因此,这里需要做的是检查regex返回的值是否不是
None


也就是说,
如果n不是None:
其他答案都是正确的,但它确实比你所做的要简单得多

出现错误是因为re.match使用字符串而不是整数,因此需要:

number = input("Enter a number of variable length e.g. 73618 :")
此外,如果re不匹配,它将返回None。“无”与“假”不同:

if n is not None: ...
如果你混合使用数字和字母(例如9f),它也不起作用。不过,解决方案非常简单。您根本不需要使用re:

number = input("Enter a number of variable length e.g. 73618 :")

if number.isdigit():
    total = 0 
        for digit in number: 
            total += digit
            print ("The total sum of digits is:",total)
else:
    print("Error! Make sure you only use numbers")

其他的答案都是正确的,但实际上比你做的要简单得多

出现错误是因为re.match使用字符串而不是整数,因此需要:

number = input("Enter a number of variable length e.g. 73618 :")
此外,如果re不匹配,它将返回None。“无”与“假”不同:

if n is not None: ...
如果你混合使用数字和字母(例如9f),它也不起作用。不过,解决方案非常简单。您根本不需要使用re:

number = input("Enter a number of variable length e.g. 73618 :")

if number.isdigit():
    total = 0 
        for digit in number: 
            total += digit
            print ("The total sum of digits is:",total)
else:
    print("Error! Make sure you only use numbers")

如果您只想输入一个数字,那么正则表达式在这里可能有点过头了。当您使用Python的
int()
函数将字符串转换为数字时,如果字符串包含字母,则会出现错误。您可以使用以下异常处理捕获此异常:

try:        
    number_string = input("Enter a number of variable length e.g. 73618 : ")
    number = int(number_string)  # try and convert the string into a number
    total = 0 
    for digit in number_string: 
        total += int(digit)
    print ("The total sum of digits is:", total)    

except ValueError as e:
    print ("Error! Make sure you only use numbers") 
您还可以使用Python的
sum()
函数来帮助合计:

try:        
    number_string = input("Enter a number of variable length e.g. 73618 : ")
    number = int(number_string)  # try and convert the string into a number

    total = sum(int(digit) for digit in number_string) 
    print ("The total sum of digits is:", total)    

except ValueError as e:
    print ("Error! Make sure you only use numbers")

如果您只想输入一个数字,那么正则表达式在这里可能有点过头了。当您使用Python的
int()
函数将字符串转换为数字时,如果字符串包含字母,则会出现错误。您可以使用以下异常处理捕获此异常:

try:        
    number_string = input("Enter a number of variable length e.g. 73618 : ")
    number = int(number_string)  # try and convert the string into a number
    total = 0 
    for digit in number_string: 
        total += int(digit)
    print ("The total sum of digits is:", total)    

except ValueError as e:
    print ("Error! Make sure you only use numbers") 
您还可以使用Python的
sum()
函数来帮助合计:

try:        
    number_string = input("Enter a number of variable length e.g. 73618 : ")
    number = int(number_string)  # try and convert the string into a number

    total = sum(int(digit) for digit in number_string) 
    print ("The total sum of digits is:", total)    

except ValueError as e:
    print ("Error! Make sure you only use numbers")