UNICEF donations: Ajude-nos a Ajudar: -UNICEF Portugal https://donativos.unicef.pt/campanha/ost-fome-pledge/
Example 1: Full IBAN PT50 0033 0000 5013 1901 2290 5
Example 2: NIB without country (defaults to PT) PT50 0033 0000 5013 1901 2290 5
UNICEF donations: Ajude-nos a Ajudar: -UNICEF Portugal https://donativos.unicef.pt/campanha/ost-fome-pledge/
Example 1: Full IBAN PT50 0033 0000 5013 1901 2290 5
Example 2: NIB without country (defaults to PT) PT50 0033 0000 5013 1901 2290 5
| #!/usr/bin/env python | |
| """ ibanformatter.py | |
| With simple tests. | |
| """ | |
| def main(): | |
| # Example usage | |
| print( | |
| "UNICEF donations: Ajude-nos a Ajudar:\n", | |
| "-UNICEF Portugal https://donativos.unicef.pt/campanha/ost-fome-pledge/", | |
| sep="", end="\n\n", | |
| ) | |
| print("Example 1: Full IBAN") | |
| if1 = IbanFormatter("PT50003300005013190122905") | |
| print(if1.pretty(), end="\n\n") | |
| print("Example 2: NIB without country (defaults to PT)") | |
| if2 = IbanFormatter("003300005013190122905") | |
| print(if2.pretty(), end="\n\n") | |
| return if1 | |
| class IbanFormatter: | |
| COUNTRY_PREFIXES = { | |
| "Portugal": "PT50", | |
| "Germany": "DE00", | |
| "Spain": "ES00", | |
| "France": "FR00", | |
| "Italy": "IT00", | |
| } | |
| def __init__(self, raw_value, country=None): | |
| self.raw_value = raw_value.replace(" ", "") | |
| self.country = country | |
| # If user did not specify a country, assume Portugal | |
| if self.country is None: | |
| self.prefix = self.COUNTRY_PREFIXES["Portugal"] | |
| self.country = "Portugal" | |
| else: | |
| self.prefix = self.COUNTRY_PREFIXES.get(self.country, None) | |
| if self.prefix is None: | |
| raise ValueError(f"Unknown country: {self.country}") | |
| # If the input already starts with a country prefix, keep it | |
| if self.raw_value[:2].isalpha(): | |
| self.iban = self.raw_value | |
| else: | |
| # Treat as NIB and prepend prefix | |
| self.iban = self.prefix + self.raw_value | |
| def compact(self): | |
| """Return IBAN without spaces.""" | |
| return self.iban | |
| def pretty(self): | |
| """Return IBAN grouped in blocks of 4 characters.""" | |
| s = self.iban | |
| return " ".join(s[i:i+4] for i in range(0, len(s), 4)) | |
| def country_name(self): | |
| """Return the country name.""" | |
| return self.country | |
| def bank_code(self): | |
| """Return the bank code (digits 5–8 for PT IBANs).""" | |
| if len(self.iban) < 8: | |
| return None | |
| return self.iban[4:8] | |
| def __str__(self): | |
| return self.pretty() | |
| if __name__ == "__main__": | |
| main() |