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

Time:06-04

I am not too sure if I worded the title correctly but what I am attempting to do is if the while loop detects that the new_string did indeed remove punctuation to print that it was invalid, I am sure how I have it set-up now even if it did work correctly it would print invalid twice.

Any recommendations, or if I can even get this to work correctly using the string module.

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()  

I know I would have to call back into the main function for it to print invalid, somehow just not sure how.

I was hoping this would be a "faster" more efficient way instead of creating a list with all the punctuations then a million if statements.

CodePudding user response:

You could go and turn

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

to

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

So, full code is

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()

which should print if there were and punctuations, assuming they were stripped from translate

  • Related