I am trying to generate barcodes in an app to tag the products which includes 3 things:
Something like this:
def get(self, request, *args, **kwargs):
pk = self.kwargs['pk']
grn = Grn.objects.filter(pk=pk)[0]
grn_prod = grn.items.all()
items = []
for i in grn_prod:
for j in range(i.item_quantity):
items.append("YNT" + str(pk) + str(i.item.pk) + str(j + 1))
It generates a sequence like the following:
YNT55232
Which is good but while scanning it if I want to know the item ID
or Serial ID
the it becomes a problem as it could be 23, 523, 3, etc.
For this I want to specify a no of digits for GRN
, Product
and Serial Id
something like this:
GRN Barcode GRN ID Product ID Serial ID
YNT 000X 000X 0000X
I am unable to figure out how to append 0
before the IDs
?
you can use format
in Python. It is commonly used to format many variables.
If you want to format this: "YNT" + str(pk) + str(i.item.pk) + str(j + 1)
you can use format
as below:
'"YNT"\t{:04d}\t{:04d}\t{:05d}'.format(pk, i.item.pk, j+1)
In case you do not know; the {}
are for each variable as in order in format()
.
As you want to have pk
and i.item.pk
as four characters, then you add :04d
. :04d
completes the words with 0. For instance;
if pk = 1
, then it converts it to 0001
, or if it is 101
then it converts to 0101
.
Same is for j+1
, if j+1
is 1, then it generates 00001
, if it is 101
, then it generates 00101
.
If you have not used format in Python, I suggest you learn it. It is really helpful for formatting variables.
Thezfill
function does exactly this. str.zfill(5)
will pad given string in variable str
to at least 5 characters, for example.
There are different ways to achieve String formatting .
Look at the above mention documentation of string function zfill
. A box follows that explains:
printf style String Formatting using the %
operator (modulo):
barcode = '%(gnr)03d%(product)03d%(serial)04d' % {'gnr': 123, 'product': 456, 'serial': 7890}
print(barcode)
produces YNT1234567890
.
You can also use the Python 3 way with f-strings :
# barcode components readable named
gnr = pk
product = i.item.pk
serial = j + 1
# format-literal simply will replace the variables named
barcode = f"YNT{gnr:03}{product:03}{serial:04}"
items.append(barcode)
It uses a prefix after the variable-name:
:0x
for left-padding with x leading zeros. Note: I always clearly named the template-variables (here: barcode components):
So we can use a readable template also called format-literal like: "{component_1} before {component_2} then {the_rest}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.