python - 在 python 中返回 1 而不是 true

标签 python python-2.7 boolean

我试图在 python 中返回一个而不是 true。

我正在处理的代码是:

delimiters = ( '()', '[]', '{}', "''", '""' )
esc = '\\'

def is_balanced(s, delimiters=delimiters, esc=esc):
    stack = []
    opening = tuple(str[0] for str in delimiters)
    closing = tuple(str[1] for str in delimiters)
    for i, c in enumerate(s):
        if len(stack) and stack[-1] == -1:
            stack.pop()
        elif c in esc:
            stack.append(-1)
        elif c in opening and (not len(stack) or opening[stack[-1]] != closing[stack[-1]]):
            stack.append(opening.index(c))
        elif c in closing:
            if len(stack) == 0 or closing.index(c) != stack[-1]:
                return False
            stack.pop()

    return len(stack) == 0

num_cases = raw_input()
num_cases = int(num_cases)
for num in range(num_cases):
    s = raw_input()
    print is_balanced(s)

它主要检查输入的字符串是否平衡。如果平衡,应返回 1,否则返回 0。

我试过这个:

1
Test string
True

它返回真。我希望它返回 1。我该怎么做?

最佳答案

或者,您可以将 boolean 值转换为 int:

>>>myBoolean = True
>>>int(myBoolean)
1
>>>myBoolean = False
>>>int(myBoolean)
0

关于python - 在 python 中返回 1 而不是 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12386196/

相关文章:

python - NumPy 2D 数组 boolean 索引与每个轴

c - 如何将 const uint8_t * const 转换为 bool

Python ElementTree 支持解析未知 XML 实体?

python - 重复 B 列中的值,直到 A 列发生变化

python - Cython 使用内存 View 崩溃

python-2.7 - 如何在没有root的情况下安装python-dev?

python-2.7 - 通过网络摄像头检测

c - 未初始化的 _Bool 变量或结构字段行为异常

python - 根据python中的列表替换列中的几个值

python - TKinter 中的 RTL(从右到左)语言