How to check if the string is numbers and then apply the condition?

I have a zip code data in text file coming from conversion of excel to text file, and I want to check if the country is USA then add trailing zeros in the zip code if it is less than 5 digits.

FYI - you can’t take the length as a criteria, as according to the requirements the zip code is hard coded to take 6 spaces(rest goes blank if the code is less than 6)

Example : In excel -
Country : USA
zip : 457

Result in text file:
Country : USA
Zip : 00457(space)

To check if the string only consists of numbers, use .isdigit() built-in function.:


to apply the condition (add zeroes if length less than 5), use len() and string concatenation.:

if len(zipCode) < 5:
    zipCode = "0" * (5 - len(zipCode)) + zipCode

zipCode before: "457" (length: 3)
zipCode after "00457" (length: 5, remaining 2 filled with zeroes)

To clarify, zipCode is the variable containing the zip code to check and apply the condition.