1111############
1212
1313
14- def format_cep (cep : str , only_nums = False ) -> str | None :
14+ def remove_symbols (dirty : str ) -> str :
15+ """
16+ Removes specific symbols from a given CEP (Postal Code).
17+
18+ This function takes a CEP (Postal Code) as input and removes all occurrences
19+ of the '.' and '-' characters from it.
20+
21+ Args:
22+ cep (str): The input CEP (Postal Code) containing symbols to be removed.
23+
24+ Returns:
25+ str: A new string with the specified symbols removed.
26+
27+ Example:
28+ >>> remove_symbols("123-45.678.9")
29+ "123456789"
30+ >>> remove_symbols("abc.xyz")
31+ "abcxyz"
32+ """
33+
34+ return "" .join (filter (lambda char : char not in ".-" , dirty ))
35+
36+
37+ def format_cep (cep : str ) -> str | None :
1538 """
1639 Formats a Brazilian CEP (Postal Code) into a standard format.
1740
18- This function takes a CEP (Postal Code) as input and,
19- - Removes special characteres;
20- - Check if the string follows the CEP length pattern;
21- - Returns None if the string is out of the pattern;
22- - Return a string with the formatted CEP.
41+ This function takes a CEP (Postal Code) as input and, if it is a valid
42+ 8-digit CEP, formats it into the standard "12345-678" format.
2343
2444 Args:
2545 cep (str): The input CEP (Postal Code) to be formatted.
@@ -31,27 +51,11 @@ def format_cep(cep: str, only_nums=False) -> str | None:
3151 Example:
3252 >>> format_cep("12345678")
3353 "12345-678"
34- >>> format_cep(" 12.345/678 ", only_nums=True)
35- "12345678"
3654 >>> format_cep("12345")
3755 None
3856 """
39- ### Checking data type
40- if not isinstance (cep , str ):
41- return None
42-
43- ### Removing special characteres
44- cep = "" .join (filter (str .isalnum , cep ))
45-
46- ### Checking CEP patterns
47- if len (cep ) != 8 :
48- return None
4957
50- ### Returning CEP value
51- if only_nums :
52- return cep
53- else :
54- return f"{ cep [:5 ]} -{ cep [5 :]} "
58+ return f"{ cep [:5 ]} -{ cep [5 :8 ]} " if is_valid (cep ) else None
5559
5660
5761# OPERATIONS
@@ -152,7 +156,7 @@ def get_address_from_cep(
152156 """
153157 base_api_url = "https://viacep.com.br/ws/{}/json/"
154158
155- clean_cep = format_cep (cep , only_nums = True )
159+ clean_cep = remove_symbols (cep )
156160 cep_is_valid = is_valid (clean_cep )
157161
158162 if not cep_is_valid :
0 commit comments