I am pulling data from a spreadsheet and one of the columns has leading zeroes. The zeros get trimmed when the data comes in. I need the preceding zeroes for the data transfer. Also, I need the format to always be four-digits.
Note: This example is distilled for simplification
For example:
Spreadsheet
lastname | firstname | id_number | notes |
---|---|---|---|
smith | john | 0008 | test |
jones | sally | 0123 | test |
baggins | bilbo | 4787 | test |
Python code:
import openpyxl
from openpyxl.descriptors.base import String
wrkbk = openpyxl.load_workbook(r"C:\Users\Philomathean\Desktop\Temp\ID.xlsx")
ws = wrkbk.active
rows = ws.iter_rows()
for LastName, FirstName, ID, Notes in rows:
result = (f"The ID should be 4 digits with leading zeroes for less than four digits: '{ID.value}'")
f = open("C:\\Users\\CPRITCHARD\\Desktop\\Temp\\Example.txt", "a")
f.write(f'{result}\n')
f.close()
EXPECTED RESULTS:
- The ID should be 4 digits with leading zeroes for less than four digits: '0008'
- The ID should be 4 digits with leading zeroes for less than four digits: '0123'
- The ID should be 4 digits with leading zeroes for less than four digits: '4787'
ACTUAL RESULTS:
- The ID should be 4 digits with leading zeroes for less than four digits: '8'
- The ID should be 4 digits with leading zeroes for less than four digits: '28'
- The ID should be 4 digits with leading zeroes for less than four digits: '62'
It's not clear whether
ID.value
is a string or integer. If it is an integer:result = (f"The ID should be 4 digits with leading zeroes for less than four digits: '{ID.value:04d}'")
If it is a string:
result = (f"The ID should be 4 digits with leading zeroes for less than four digits: '{ID.value.zfill(4)}'")