Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a custom mask into a string of digits in Python?

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.

like image 352
Bruno Calza Avatar asked Nov 14 '14 00:11

Bruno Calza


Video Answer


2 Answers

With your syntax, you need to make a tuple, instead of a joined comma-separated string, since the latter is treated as one supplied string argument, hence the error you're experiencing:

'%s%s/%s%s/%s%s%s%s' % tuple('13082004')

Or, use the newer string .format() method, with the * operator to unpack the string into multiple arguments:

'{}{}/{}{}/{}{}{}{}'.format(*'13082004')
like image 120
jayelm Avatar answered Sep 30 '22 16:09

jayelm


mask = '%s%s/%s%s/%s%s%s%s'
mask % tuple('13082004')

running the code above will result in:

'13/08/2004'
like image 32
helloV Avatar answered Sep 30 '22 17:09

helloV