string.py 872 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import re
  2. __all__ = (
  3. 'enum_key',
  4. 'remove_linebreaks',
  5. 'title',
  6. 'trailing_slash',
  7. )
  8. def enum_key(value):
  9. """
  10. Convert the given value to a string suitable for use as an Enum key.
  11. """
  12. value = str(value).upper()
  13. return re.sub(r'[^_A-Z0-9]', '_', value)
  14. def remove_linebreaks(value):
  15. """
  16. Remove all line breaks from a string and return the result. Useful for log sanitization purposes.
  17. """
  18. return value.replace('\n', '').replace('\r', '')
  19. def title(value):
  20. """
  21. Improved implementation of str.title(); retains all existing uppercase letters.
  22. """
  23. return ' '.join([w[0].upper() + w[1:] for w in str(value).split()])
  24. def trailing_slash(value):
  25. """
  26. Remove a leading slash (if any) and include a trailing slash, except for empty strings.
  27. """
  28. return f'{value.strip("/")}/' if value else ''