简体   繁体   English

Python - 将 9 位数字 integer 转换为格式为“xxx-xx-xxxx”的字符串

[英]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.我正在为我所在的 python 课程做一些练习题,但我对其中一个问题有点迷茫。 The task seems relatively simple:任务看起来相对简单:

Create a solution that accepts an integer input representing a 9-digit unformatted student identification number.创建一个接受 integer 输入的解决方案,该输入表示 9 位未格式化的学生标识号。 Output the identification number as a string with no spaces. Output 作为不带空格的字符串的标识号。 The solution should be in the format: 111-22-3333.解决方案的格式应为:111-22-3333。 So if the input is "154175430" then the expected output is "154-17-5430".因此,如果输入为“154175430”,则预期的 output 为“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?我只是想知道如果您只是将 integer 转换为字符串,您将如何或为什么使用模除法或底除法? 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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