Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- def is_valid_cpf(cpf):
- """Check if a 11-numbers-only Brazilian CPF string is valid
- Parameters
- ----------
- cpf: string
- 11-numbers-only Brazilian CPF
- Returns
- -------
- True or False
- Raises
- ------
- None
- Examples
- --------
- >>> cpf1 = '06670116098'
- >>> print(is_valid_cpf(cpf1))
- True
- >>> cpf2 = '06670116099'
- >>> print(is_valid_cpf(cpf2))
- False
- >>> cpf3 = '0667011609A'
- >>> print(is_valid_cpf(cpf3))
- False
- >>> cpf4 = '0667011'
- >>> print(is_valid_cpf(cpf4))
- False
- See Also
- --------
- https://djangosnippets.org/snippets/10601/
- """
- cpf = str(cpf)
- # Strip all whitespaces
- cpf = re.sub(r'\s+', '', cpf)
- # Remove punctuation
- cpf = re.sub(r'[^\w\s]', '', cpf)
- # The method isdigit() checks whether the string consists of digits only.
- if not cnpj.isdigit():
- return False
- if len(cpf) != 11:
- return False
- orig_dv = cpf[-2:]
- new_1dv = sum([i * int(cpf[idx]) for idx, i in enumerate(range(10, 1, -1))])
- if (new_1dv % 11) >= 2:
- new_1dv = 11 - (new_1dv % 11)
- else:
- new_1dv = 0
- cpf = cpf[:-2] + str(new_1dv) + cpf[-1]
- new_2dv = sum([i * int(cpf[idx]) for idx, i in enumerate(range(11, 1, -1))])
- if (new_2dv % 11) >= 2:
- new_2dv = 11 - (new_2dv % 11)
- else:
- new_2dv = 0
- cpf = cpf[:-1] + str(new_2dv)
- if cpf[-2:] != orig_dv:
- return False
- return True
- def is_valid_cnpj(cnpj):
- """Check if a 14-numbers-only Brazilian CNPJ string is valid
- Parameters
- ----------
- cpf: string
- 11-numbers-only Brazilian CPF
- Returns
- -------
- True or False
- Raises
- ------
- ValueError
- If cnpj contains alphabet chars
- Examples
- --------
- >>> cnpj1 = '57375425000100'
- >>> print(is_valid_cnpj(cnpj1))
- True
- >>> cnpj2 = '73787162000190'
- >>> print(is_valid_cnpj(cnpj2))
- False
- >>> cnpj3 = '73787162000A90'
- >>> print(is_valid_cnpj(cnpj3))
- False
- >>> cnpj4 = '73787162000'
- >>> print(is_valid_cnpj(cnpj4))
- False
- See Also
- --------
- https://djangosnippets.org/snippets/10601/
- """
- cnpj = str(cnpj)
- # Strip all whitespaces
- cnpj = re.sub(r'\s+', '', cnpj)
- # Remove punctuation
- cnpj = re.sub(r'[^\w\s]', '', cnpj)
- # The method isdigit() checks whether the string consists of digits only.
- if not cnpj.isdigit():
- return False
- if len(cnpj) != 14:
- return False
- orig_dv = cnpj[-2:]
- new_1dv = sum([i * int(cnpj[idx]) for idx, i in enumerate(list(range(5, 1, -1)) + list(range(9, 1, -1)))])
- if (new_1dv % 11) >= 2:
- new_1dv = 11 - (new_1dv % 11)
- else:
- new_1dv = 0
- cnpj = cnpj[:-2] + str(new_1dv) + cnpj[-1]
- new_2dv = sum([i * int(cnpj[idx]) for idx, i in enumerate(list(range(6, 1, -1)) + list(range(9, 1, -1)))])
- if (new_2dv % 11) >= 2:
- new_2dv = 11 - (new_2dv % 11)
- else:
- new_2dv = 0
- cnpj = cnpj[:-1] + str(new_2dv)
- if cnpj[-2:] != orig_dv:
- return False
- return True
Advertisement
Add Comment
Please, Sign In to add comment