Given a custom mask like ##/##/#### or (###) ###-#### and a string of digits that has a length equals to the number of # of the custom mask,
How can a define a function called format that applies a custom mask to a string?
For example:
> format('##/##/####','13082004')
13/08/2004
In PHP I can use vsprintf to achieve this:
function format($mask,$string)
{
return vsprintf($mask, str_split($string));
}
$mask = "%s%s.%s%s%s.%s%s%s/%s%s%s%s-%s%s";
echo format($mask,'11622112000109');
11.622.112/0001-09
I tried something similar with Python using % operator
mask = '%s%s/%s%s/%s%s%s%s'
mask % ', '.join(list('13082004'))
But,
TypeError: not enough arguments for format string not enough arguments for format string
I know why I am getting this error, but can pass this point. Any solution is welcome.
With your syntax, you need to make a
tuple, instead of ajoined comma-separated string, since the latter is treated as one supplied string argument, hence the error you're experiencing:Or, use the newer string
.format()method, with the*operator to unpack the string into multiple arguments: