使用字符串模块循环,如果翻译方法有效则打印一条消息

Using string module to loop, and print a message if the translate method works

我不太确定标题的措辞是否正确,但我想做的是,如果 while 循环检测到 new_string 确实删除了标点符号以打印它无效,我确定我是怎么得到它的 set-up 现在即使它确实工作正常它也会打印两次无效。

任何建议,或者我什至可以使用字符串模块使其正常工作。

import string


def main():
    plate = input("Plate: ")
    exclusions(plate)
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def exclusions(s):
    new_string = s.translate(
        str.maketrans('', '', string.punctuation))
    while len(new_string) < is_valid(s):
        if new_string == True:
            print("Invalid\nPlease do not use punctuation")
    print(new_string)


def is_valid(s):
    return 2 <= len(s) <= 6


main()  

我知道我必须回调到 main 函数才能打印无效,只是不知道怎么做。

我希望这将是一种“更快”更有效的方法,而不是创建一个包含所有标点符号的列表,然后是一百万个 if 语句。

你可以去转弯

    while len(new_string) < is_valid(s):
        if new_string == True:
            print("Invalid\nPlease do not use punctuation")

    if len(new_string) < len(s):
        print("Please do not use punctuation")
        print(new_string)
        return True
    else:
        return False

所以,完整代码是

import string


def main():
    plate = input("Plate: ")
    return_val = exclusions(plate)

    if return_val:
        print("Invalid")
    else:
        print("Valid")


def exclusions(s):
    new_string = s.translate(
        str.maketrans('', '', string.punctuation))
    if len(new_string) < len(s):
        print("Please do not use punctuation")
        print(new_string)
        return True
    else:
        return False


main()

如果有和标点符号应该打印出来,假设它们从翻译中删除