• Coding

    Python Learning: Automate Boring Stuff with Python | Solution to Part II Chapter 7 Practice Project II

    [sourcecode language=”python”]</pre> import re #first argument – string to be stripped #second argument – char or default " " def customStrip(string: str, stripChar: str="\s")->str: ”’ Removes specified character from the beginning and end of a given string arguments: string: str stripChar: str returns: string ”’ if stripChar == "" or stripChar == " ": stripChar = "\s" patternString = r"({}+)".format(stripChar) actions = ("^" + patternString,patternString + "$") for p in actions: pattern = re.compile(p) string = pattern.sub("",string) return string texts = [ " aa dfgfhjgs, afktgrg aaa ", "aaaaaaaaaaaaaaaajfdgf fdfgjkerturt aaaaa" ] for text in texts: st = customStrip(text, "a") print("The text \n{}\n has {}characters.\nAfter strip \n{} \n====\n it now…

  • Coding

    Python Learning: Automate Boring Stuff with Python | Solution to Part II Chapter 7 Practice Project I

    [sourcecode language=”python”]</pre> <pre> import re import re  #eight chars long #upper and lower case chars #at least one digit patternHasDigit = re.compile(r"\d+") patternHasLower = re.compile(r"[a-z]+") patternHasUpper = re.compile(r"[A-Z]+") patterns = (patternHasDigit, patternHasLower, patternHasUpper) tests = ["asdfgh57887", "Asfkg35a", "23454990-","ASHGFDSFGHFDSDFGDS"] for test in tests: status = True for pattern in patterns: if pattern.search(test) == None: print("{} failed {} test".format(test, pattern.pattern)) status = False if status: print("{} did match".format(test)) else: print("{} did not match".format(test)) status = True [/sourcecode] Please follow and like us:0

Enjoy this blog? Please spread the word :)

error: Content is protected !!