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

Time:11-13

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.

CodePudding user response:

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
  • Related