sh_cpl/src/cpl_core/utils/string.py

92 lines
2.2 KiB
Python
Raw Normal View History

2021-03-10 22:11:05 +01:00
import re
2021-04-11 13:00:05 +02:00
import string
import random
2021-03-10 22:11:05 +01:00
class String:
2021-05-17 18:07:08 +02:00
r"""Useful functions for strings"""
2021-03-10 22:11:05 +01:00
@staticmethod
2021-04-11 13:00:05 +02:00
def convert_to_camel_case(chars: str) -> str:
2021-05-17 18:07:08 +02:00
r"""Converts string to camel case
Parameter
---------
chars: :class:`str`
String to convert
Returns
-------
String converted to CamelCase
2021-04-11 13:00:05 +02:00
"""
converted_name = chars
char_set = string.punctuation + ' '
for char in char_set:
if char in converted_name:
converted_name = ''.join(word.title() for word in converted_name.split(char))
return converted_name
@staticmethod
def convert_to_snake_case(chars: str) -> str:
2021-05-17 18:07:08 +02:00
r"""Converts string to snake case
Parameter
---------
chars: :class:`str`
String to convert
Returns
-------
String converted to snake_case
2021-03-14 16:06:23 +01:00
"""
# convert to train-case to CamelCase
2021-04-11 13:00:05 +02:00
if '-' in chars:
chars = ''.join(word.title() for word in chars.split('-'))
2021-03-10 22:11:05 +01:00
pattern1 = re.compile(r'(.)([A-Z][a-z]+)')
pattern2 = re.compile(r'([a-z0-9])([A-Z])')
2021-04-11 13:00:05 +02:00
file_name = re.sub(pattern1, r'\1_\2', chars)
return re.sub(pattern2, r'\1_\2', file_name).lower()
@staticmethod
2021-04-11 13:00:05 +02:00
def first_to_upper(chars: str) -> str:
2021-05-17 18:07:08 +02:00
r"""Converts first char to upper
Parameter
---------
chars: :class:`str`
String to convert
Returns
-------
String with first char as upper
2021-03-14 16:06:23 +01:00
"""
2021-04-11 13:00:05 +02:00
return f'{chars[0].upper()}{chars[1:]}'
@staticmethod
2021-04-11 13:00:05 +02:00
def first_to_lower(chars: str) -> str:
2021-05-17 18:07:08 +02:00
r"""Converts first char to lower
Parameter
---------
chars: :class:`str`
String to convert
Returns
-------
String with first char as lower
2021-03-14 16:06:23 +01:00
"""
2021-04-11 13:00:05 +02:00
return f'{chars[0].lower()}{chars[1:]}'
@staticmethod
def random_string(chars: str, length: int) -> str:
2021-05-17 18:07:08 +02:00
r"""Creates random string by given chars and length
Returns
-------
String of random chars
2021-04-11 13:00:05 +02:00
"""
return ''.join(random.choice(chars) for _ in range(length))