How to generate a string consisting of 16 digits but between every 4 numbers there is a hyphen(-)?
Question:
What kind of technique would allow me to generate a string in Python similar to this output:
1234-1234-1234-1234
Answers:
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
What kind of technique would allow me to generate a string in Python similar to this output:
1234-1234-1234-1234
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