简体   繁体   中英

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

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?

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

I am assuming an answer similar to this is wanted:

def int2student_id(in_val:int):
    start = in_val//1000000
    middle = in_val//10000%100
    end = in_val%10000
    return str(start) + '-' + str(middle) + '-' + str(end)

print(int2student_id(154175430))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM