Home > database >  Python - Converting a 9 digit integer into a string with the format of "xxx-xx-xxxx"
Python - Converting a 9 digit integer into a string with the format of "xxx-xx-xxxx"

Time:12-08

I was working on some practice problems for a python course i am in and I was a little lost on one of the questions. The task seems relatively simple:

Create a solution that accepts an integer input representing a 9-digit unformatted student identification number. Output the identification number as a string with no spaces. The solution should be in the format: 111-22-3333. So if the input is "154175430" then the expected output is "154-17-5430".

This seems pretty straightforward, however once i looked at the initial coding comments they gave us to start the program, the first line of comment read:

# hint: modulo (%) and floored division(//) may be used

This hint is what really tripped me up. I was just wondering how or why you would use a modulo or floored division if you are just converting an integer to a string? I assume it has to do with the formatting to get the "-" in between the necessary digits?

CodePudding user response:

Going the floor division and modulus route we can try:

num = 154175430
output = str(num / 1000000)   "-"   str((num / 10000) % 100)   "-"   str(num % 10000)
print(output)  # 154-17-5430

We could also be lazy and use a regex replacement:

num = 154175430
output = re.sub(r'(\d{3})(\d{2})(\d{4})', r'\1-\2-\3', str(num))
print(output)  # 154-17-5430

CodePudding user response:

I am assuming an answer similar to this is wanted:

def int2student_id(in_val:int):
    start = in_val//1000000
    middle = in_val//100000
    end = in_val000
    return str(start)   '-'   str(middle)   '-'   str(end)

print(int2student_id(154175430))
  • Related