1111############
1212
1313
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 :
14+ def format_cep (cep : str , only_nums = False ) -> str | None :
3815 """
3916 Formats a Brazilian CEP (Postal Code) into a standard format.
4017
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.
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.
4323
4424 Args:
4525 cep (str): The input CEP (Postal Code) to be formatted.
@@ -51,11 +31,27 @@ def format_cep(cep: str) -> str | None:
5131 Example:
5232 >>> format_cep("12345678")
5333 "12345-678"
34+ >>> format_cep(" 12.345/678 ", only_nums=True)
35+ "12345678"
5436 >>> format_cep("12345")
5537 None
5638 """
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
5749
58- return f"{ cep [:5 ]} -{ cep [5 :8 ]} " if is_valid (cep ) else None
50+ ### Returning CEP value
51+ if only_nums :
52+ return cep
53+ else :
54+ return f"{ cep [:5 ]} -{ cep [5 :]} "
5955
6056
6157# OPERATIONS
@@ -156,7 +152,7 @@ def get_address_from_cep(
156152 """
157153 base_api_url = "https://viacep.com.br/ws/{}/json/"
158154
159- clean_cep = remove_symbols (cep )
155+ clean_cep = format_cep (cep , only_nums = True )
160156 cep_is_valid = is_valid (clean_cep )
161157
162158 if not cep_is_valid :
0 commit comments