How to format cpf correctly in python?

3

I have the following code:

test = input ("CPF: ") 

When the CPF is entered:

12345678900

But when I return this input it returns:

123.456.789-00

How do I do this in Python?

    
asked by anonymous 14.09.2017 / 18:05

3 answers

1

A test should be included if the CPF has 11 digits and zeros to the left if fewer digits, so the 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
    
10.09.2018 / 22:48
3

It's as simple as this:

test = input ("CPF: ") 
cpf = test[:3] + "." + test[3:6] + "." + test[6:9] + "-" + test[9:]
print(cpf)

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

    
14.09.2017 / 18:15
3

If this formatting is always the case, then I agree with @bigown in comment, you do not need a class for this at all, you can do this:

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

DEMONSTRATION

    
14.09.2017 / 18:14