as_string.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #############################################################################
  2. ##
  3. ## Copyright (c) 2026 Riverbank Computing Limited <info@riverbankcomputing.com>
  4. ##
  5. ## This file is part of PyQt6.
  6. ##
  7. ## This file may be used under the terms of the GNU General Public License
  8. ## version 3.0 as published by the Free Software Foundation and appearing in
  9. ## the file LICENSE included in the packaging of this file. Please review the
  10. ## following information to ensure the GNU General Public License version 3.0
  11. ## requirements will be met: http://www.gnu.org/copyleft/gpl.html.
  12. ##
  13. ## If you do not wish to use this file under the terms of the GPL version 3.0
  14. ## then you may purchase a commercial license. For more information contact
  15. ## info@riverbankcomputing.com.
  16. ##
  17. ## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
  18. ## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  19. ##
  20. #############################################################################
  21. import re
  22. def as_string(obj):
  23. if isinstance(obj, str):
  24. return '"' + _escape(obj) + '"'
  25. return str(obj)
  26. _esc_regex = re.compile(r"(\"|\'|\\)")
  27. def _escape(text):
  28. # This escapes any escaped single or double quote or backslash.
  29. x = _esc_regex.sub(r"\\\1", text)
  30. # This replaces any '\n' with an escaped version and a real line break.
  31. return re.sub(r'\n', r'\\n"\n"', x)