From a82dc30d431577a835c18045fde23aec62cc883c Mon Sep 17 00:00:00 2001 From: the-holger Date: Thu, 29 Sep 2022 09:22:52 +0200 Subject: [PATCH] Added ASCII string representations ASCII string representations as get_ascii as well as __str__ to quickly print and use a QrCode in the terminal. --- python/qrcodegen.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/python/qrcodegen.py b/python/qrcodegen.py index 5d84c39..77de4c1 100644 --- a/python/qrcodegen.py +++ b/python/qrcodegen.py @@ -228,6 +228,28 @@ class QrCode: If the given coordinates are out of bounds, then False (light) is returned.""" return (0 <= x < self._size) and (0 <= y < self._size) and self._modules[y][x] + def get_ascii(self, white_pixel_char: str = "██", black_pixel_char: str = " ") -> str: + """Returns a string containing the visual representation of the QrCode as an ASCII + character encoded string. The ASCII characters to be used can be defined as + white_pixel_char and black_pixel_char.""" + ascii_string = "" + for y in range(self._size): + for x in range(self._size): + if self.get_module(x,y): + ascii_string += white_pixel_char + else: + ascii_string += black_pixel_char + ascii_string += "\n" + return ascii_string[:-1] + + + # ---- Dunder methods ---- + + def __str__(self) -> str: + """Returns a string containing the visual representation of the QrCode as an ASCII + character encoded string.""" + return self.get_ascii() + # ---- Private helper methods for constructor: Drawing function modules ----