简体   繁体   English

while循环多个条件的Python

[英]while loop multiple conditions Python

Hello, I have the following function: 您好,我有以下功能:

def width(input,output,attr):
    import re
    input = input.strip()
    if re.search(attr, input):
        k = input.find(attr)
        for i in input:
            if i == attr[0]:
                j = k + len(attr)+1
                while ((j <= len(input)) |  (j != ' ') | (input[j+1] != "'")):
                    j = j + 1
                    #print j, output, input[j], len(input), k
                    output = output+input[j]
                break
            k = k + 1
    return output

print width('a=\'100px\'','','a')

I get always get the following error: 我总是得到以下错误:

Traceback (most recent call last):
  File "table.py", line 45, in <module>
    print width(split_attributes(w,'','<table.*?>'),'','width')
  File "table.py", line 24, in width
    while ((j <= len(input)) |  (j != ' ') | (input[j+1] != "'")):
IndexError: string index out of range

I have tried using or instead | 我尝试使用or代替| but it didn't work! 但这没用!

while ((j <= len(input)) |  (j != ' ') | (input[j+1] != "'")):

0) You should be using or . 0)您应该使用or

1) You should not use input as a variable name; 1)您不应将input用作变量名; it hides a built-in function. 它隐藏了内置功能。

2) j is an integer, so it can never be equal to ' ' , so that test is useless. 2) j是一个整数,所以它永远不能等于' ' ,因此测试无用。

3) j <= len(input) passes when j == len(input) . 3)当j == len(input)时, j <= len(input)通过。 The length of a string is not a valid index into the string; 字符串的长度不是该字符串的有效索引; indices into a string of length N range from 0 to (N - 1) (you can also use negative numbers from -1 to -N, to count from the end). 索引长度为N的字符串,范围从0到(N-1)(也可以使用从-1到-N的负数从末尾开始计数)。 Certainly j+1 doesn't work either. 当然j+1也不起作用。

4) I can't tell what the heck you are actually trying to do. 4)我不知道你到底想做什么。 Could you explain it in words? 你能用语言解释吗? As stated, this isn't a very good question; 如上所述,这不是一个很好的问题。 making the code stop throwing exceptions doesn't mean it's any closer to working correctly, and certainly doesn't mean it's any closer to being good code. 使代码停止抛出异常并不意味着它更接近于正常工作,当然也不意味着它与成为良好的代码更接近。

It looks like j+1 is a number greater than or equal to the length of the string you have ( input ). 看起来j+1是一个大于或等于您拥有的字符串( input )的长度的数字。 Make sure you structure your while loop so that j < (len(input) - 1) is always true and you won't end up with the string index out of range error. 确保构造while循环,以使j < (len(input) - 1)始终为true,并且不会导致字符串索引超出范围错误。

if j >= len(input) - 1 then j+1 will most certainly be out of bounds. 如果j >= len(input) - 1那么j+1肯定会超出范围。 Also, use or and not | 另外,使用or不使用| .

You get an error IndexError: string index out of range . 您收到错误IndexError: string index out of range The only index reference is in part input[j+1] . 唯一的索引参考是部分input[j+1] Situation when j = len(input) will cause an error, as the following code demonstrates: j = len(input)将导致错误,如以下代码所示:

>>> input = "test string"
>>> len(input)
11
>>> input[11]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> input[10]
'g'

If you try to reference element number j+1 , then condition j < ( len(input) - 1 ) needs to be satisfied. 如果尝试引用元素编号j+1 ,则需要满足条件j < ( len(input) - 1 )

When using != in if statements, make sure that or is actually what you need. 在if语句中使用!=时,请确保or确实是您所需要的。 Here's an example: 这是一个例子:

import random
a = random.randint(1, 10)
b = random.randint(1, 10)
c = random.randint(1, 10)
if a != 1 or b != 1 or c != 1:
    print "None of the values should equal 1"
    # The interpreter sees `a != 1`.
    # If `a` is not equal to 1 the condition is true, and this code gets excecuted.
    # This if statement will return true if ANY of the values are not equal to 1.
if a != 1 and b != 1 and c != 1:
    print "None of the values are equal to 1" # True
    # This if statement will return true if ALL of the values are not equal to 1.

This is a hard thing to understand at first (I made this mistake all the time), but if you practise it a bit, it will make perfect sense. 一开始这很难理解(我一直都犯这个错误),但是如果您稍加练习,它将很有意义。

So, to get your code working, replace those | 因此,要使您的代码正常工作,请替换这些| s with and , and it will work (and stick with the keywords or and and unless you specifically need boolean or or and ( | / & ): and ,并且可以正常工作(并坚持使用关键字orand除非您特别需要布尔值or或and和( | / & ):

while ((j <= len(input)) and  (j != ' ') and (input[j+1] != "'")):

and the output is: 输出为:

100px

Not the solution to your problem. 不能解决您的问题。 Code that probably does what you are aiming for. 可能满足您目标的代码。

Just use a single regular expression: 只需使用一个正则表达式:

import re

def width(input, attr):
    """
    >>> width("a='100px'", 'a')
    '100px'
    """
    regex = re.compile(attr + r""".*?'(?P<quoted_string>[^']+)'""")
    m = regex.match(input.strip())
    return m.group("quoted_string") if m else ''

if __name__ == '__main__':
    import doctest
    doctest.testmod()

This code skips attr and searches for a quoted string that follows. 此代码跳过attr并搜索其后的带引号的字符串。 (?P<quoted_string>[^']+) captures the quoted string. (?P<quoted_string>[^']+)捕获引用的字符串。 m.group("quoted_string") recovers the quoted string. m.group("quoted_string")恢复引用的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM