工作完成后如何停止打印?

时间:2021-07-29 06:32:41

标签: python python-3.x

因此,我的任务是为 pangram 检查器编写代码,然后显示丢失的字母。这是我到目前为止所写的:-

MAX_CHAR = 26

# Returns characters that needs
# to be added to make str
def ispanagram(Str):
    # A boolean array to store characters
    # present in string.
    present = [False for i in range(MAX_CHAR)]

    # Traverse string and mark characters
    # present in string.
    for i in range(len(Str)):
        if (Str[i] >= 'a' and Str[i] <= 'z'):
            present[ord(Str[i]) - ord('a')] = True
        elif (Str[i] >= 'A' and Str[i] <= 'Z'):
            present[ord(Str[i]) - ord('A')] = True

    # Store missing characters in alphabetic
    # order.
    res = ""

    for i in range(MAX_CHAR):
        if (present[i] == False):
            res += chr(i + ord('a')) + ", "

    return res

def main():
    Str = input()
    fg = ispanagram(Str)
    if not fg:
        print("Yes, the string is a pangram.")
    else:
        print("No, the string is NOT a pangram. Missing letter(s) is(are) " + str(fg))

if __name__ == "__main__":
    # Call the main function
    main()

结果:

inp = The quick brown fox jumps over the lazy dog
Out = Yes, the string is a pangram.
inp = Hi, I am xyz
Out = No, the string is NOT a pangram. Missing letter(s) is(are) b, c, d, e, f, g, j, k, l, n, o, p, q, r, s, t, u, v, w,

此代码工作正常,但在打印最后一个字母后会打印一个额外的逗号。我该如何阻止?

3 个答案:

答案 0 :(得分:2)

您应该使用 .join()


res=[chr(i + ord('a')) for i in range(MAX_CHAR) if present[i]==False]
return ', '.join(res)

答案 1 :(得分:0)

使用列表并加入他们:

# Use a list
res = []

for i in range(MAX_CHAR):
    if (present[i] == False):
        res.append(chr(i + ord('a')))

# Join 'em
return ', '.join(res)

答案 2 :(得分:0)

解决方案 - 1

您可以使用 res 的列表来存储字符,而不是连接到一个字符串。

然后用逗号显示它们,你可以做 - ', '.join(res)这将避免打印尾随逗号。

res = []

    for i in range(MAX_CHAR):
        if (present[i] == False):
            res.append(chr(i + ord('a')))
    
    return ', '.join(res)



def main():
    Str = input()
    fg = ispanagram(Str)
    if not fg:
        print("Yes, the string is a pangram.")
    else:
        print("No, the string is NOT a pangram. Missing letter(s) is(are) " + fg)

解决方案 - 2

使用 rstrip(', ') 去掉 res 后面的逗号。

res = ""

    for i in range(MAX_CHAR):
        if (present[i] == False):
            res += chr(i + ord('a')) + ", "

    return res.rstrip(', ')