How to properly format CPF in Python?

Asked

Viewed 7,921 times

3

I have the following code:

test = input ("CPF: ") 

When the typed CPF gets:

12345678900

But when I return this input he comes back:

123.456.789-00

How do I do it in Python?

  • 1

    See https://wiki.python.org.br/Cpf It is easy to apply Mask

  • Ah! For this case I have to create a class only for the CPF.

  • 1

    just take the groups of numbers and concatenate with the score.

  • 2

    For nothing you need to create class. Nothing. Class is something that can be useful in specific cases only for a matter of code organization, but they are always optional. Always.

5 answers

5

If it is really this format always, then I agree with @Maniero in comment, it does not need a class for this at all, you can do so:

teste = input("CPF: ") # 12345678900
cpf = '{}.{}.{}-{}'.format(teste[:3], teste[3:6], teste[6:9], teste[9:])
print(cpf) # 123.456.789-00

DEMONSTRATION

5


A test must be included if the CPF has 11 digits and fill in with zeros on the left if there are fewer digits, so formatting is correct for Cpfs starting with zero

teste = input("CPF: ") # 12345678900
if len(teste) < 11:
    teste = teste.zfill(11)
cpf = '{}.{}.{}-{}'.format(teste[:3], teste[3:6], teste[6:9], teste[9:])
print(cpf) # 123.456.789-00

3

  • Hehe, exactly the same

  • There’s no way to invent

  • Yes, bigown and Miguel! For me this is the simplest way. Since I’m learning the language now. The method of creating a class that Antharis passed I think is more evolved for me. This concatenation in Python is very simple! For God’s sake! Python is too good! Thanks guys for the tips! Work the size of the world the teacher went through.

  • Exactly, according to

  • 2

    @Sandsoncosta never falls in love with classes. Only use them when mastering the procedural very well, when you understand much about OOP and when it is really useful. One does everything so because they fall into martketing. They do not know why they are doing. Never do anything you don’t know why you’re doing, because it’s useful and beneficial. Rice and beans do most things better. Which doesn’t mean I don’t always have to evolve.

  • @Miguel doesn’t erase no

  • It was just not to be two like, but I will use format in mine to look different @bigown, obgado

Show 2 more comments

0

If you wish to use f-String to format the output of CPF, can use the following algorithm...

cpf = input('Digite o CPF: ')
if len(cpf) < 11:
    cpf = cpf.zfill(11)
print(f'{cpf[:3]}.{cpf[3:6]}.{cpf[6:9]}-{cpf[9:]}')

See here the functioning of the algorithm.

-2

The code below accepts text and number as input:

import re
def format_cpf(cpf):
    cpf = "{:0>11}".format(int(cpf))
    return re.sub("(\d{3})(\d{3})(\d{3})(\d{2})",
                  "\\1.\\2.\\3-\\4",
                  cpf)

format_cpf("123")                  

'000.000.001-23' 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.