Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i need a python code that prints out 16 digits but between every 4 numbers there is a hyphen(-)

I cant make the code I’m new to coding and I have no idea how to make it. If someone could help me with this problem it would be awesome.

I tried googling but it didn’t help and I’ve tried asking friends and they couldn’t help either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Python has a built in wrap function, made to split strings like this. In conjunction with string.join, you can rejoin the split string with your character of choice:

from textwrap import wrap

s = '1234567890abcdef'
print('-'.join(wrap(s, 4)))
>>> 1234-5678-90ab-cdef

The wrap function takes your string, and the number of characters to split on (in this case 4).
The result from this is used in '-'.join to join each element together with dashes, which gives the result you were looking for.

Note: if you’re starting with a number instead of a string, you can easily convert it using str():

s = str(1234567890123456)
print('-'.join(wrap(s, 4)))
>>> 1234-5678-9012-3456
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading