如何检查字符串中的第 n 个字母是否为非零

How to check if the n'th letter in a string is non-zero

我需要检查字符串中的第 n 个字母是否为非零。 该代码将用于检查缓冲区的输入是否会溢出缓冲区后立即存储的 auth 变量。

def test(expect, ans):
    try:
        return len(str(ans)) >= int(expect) and ans[10] is not False
    except ValueError:
        return False


def test2(expect, ans):
    try:
        return len(str(ans)) >= int(expect) and ans[15] != 0
    except ValueError:
        return False


ans1 = "asdfghjklp0"
print(ans1[10])
print(test(11, ans1))
ans2 = "1234567890123450"
print(ans2[15])
print(test2(16, ans2))

两个测试都应该 return 错误。

这对我有用:

def test(expect, ans):
    return ans[expect-1] != "0"


ans1 = "asdfghjklp0"
print(ans1[10])
print(test(11, ans1))

ans2 = "1234567890123450"
print(ans2[15])
print(test(16, ans2))

解决方案

def iszero_nth_letter(s, n=10):
    ss = s[n]
    # check if the n-th letter is a digit and 0 as well
    decision = ss.isdigit() and int(ss)==0
    return decision

print(iszero_nth_letter(s=ans1, n=10))
print(iszero_nth_letter(s=ans2, n=15))
print(iszero_nth_letter(s=ans2, n=13))

输出

True
True
False