Skip to content

Api Reference

Case Utilities

to_alternating_case(str)

Convert a string into alternating case. Uppercase letters at even indices, lowercase at odd indices.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str

A string with alternating letter cases.

Example

to_alternating_case("hello") 'HeLlO'

Source code in pystringtoolkit/cases.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def to_alternating_case(str):
    """
       Convert a string into alternating case.
       Uppercase letters at even indices, lowercase at odd indices.

       Args:
           text (str): The input string.

       Returns:
           str: A string with alternating letter cases.

       Example:
           >>> to_alternating_case("hello")
           'HeLlO'
       """
    altrnated_case = []
    for i, char in enumerate(str):
        if i % 2 == 0:
            altrnated_case.append(char.upper())
        else:
            altrnated_case.append(char.lower())
    return ''.join(altrnated_case)

to_camel_case(str)

Convert a string into camelCase.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str

A camelCased string.

Example

to_camel_case("hello world") 'helloWorld'

Source code in pystringtoolkit/cases.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def to_camel_case(str):
    """
        Convert a string into ``camelCase``.

        Args:
            text (str): The input string.

        Returns:
            str: A camelCased string.

        Example:
            >>> to_camel_case("hello world")
            'helloWorld'
        """
    str=str.title().replace(' ','')
    return str[0].lower() + str[1:]

to_kebab_case(str)

Convert a string into kebab-case.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str

A kebab-cased string.

Example

to_kebab_case("Hello World!") 'hello-world'

Source code in pystringtoolkit/cases.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def to_kebab_case(str):
    """
        Convert a string into ``kebab-case``.

        Args:
            text (str): The input string.

        Returns:
            str: A kebab-cased string.

        Example:
            >>> to_kebab_case("Hello World!")
            'hello-world'
        """
    str=str.lower()
    str = re.sub(r'[^\w\s]', '', str)
    return re.sub(r'\s+','-',str)

to_lower_case(str)

Convert a string to lowercase. If multiple words exist, keeps the first word lowercase and capitalizes the rest.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str

A string with adjusted casing.

Example

to_lower_case("HELLO WORLD") 'hello World'

Source code in pystringtoolkit/cases.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def to_lower_case(str):
    # Lowercase first word; capitalize subsequent words to match tests
    """
       Convert a string to lowercase.
       If multiple words exist, keeps the first word lowercase
       and capitalizes the rest.

       Args:
           text (str): The input string.

       Returns:
           str: A string with adjusted casing.

       Example:
           >>> to_lower_case("HELLO WORLD")
           'hello World'
       """
    lowered = str.lower()
    parts = lowered.split(' ')
    if len(parts) <= 1:
        return lowered
    first = parts[0]
    rest = [p.capitalize() if p else p for p in parts[1:]]
    return ' '.join([first] + rest)

to_pascal_case(str)

Convert a string into PascalCase.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str

A PascalCased string.

Example

to_pascal_case("hello world") 'HelloWorld'

Source code in pystringtoolkit/cases.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def to_pascal_case(str):
    """
        Convert a string into ``PascalCase``.

        Args:
            text (str): The input string.

        Returns:
            str: A PascalCased string.

        Example:
            >>> to_pascal_case("hello world")
            'HelloWorld'
        """
    return str.title().replace(' ','')

to_snake_case(str)

Source code in pystringtoolkit/cases.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def to_snake_case(str):
    str = str.lower()
    # Replace any sequence of non-alphanumeric characters (spaces/punct) with underscore
    # This preserves a trailing underscore when input ends with punctuation
    """
        Convert a string into ``snake_case``.

        Args:
            text (str): The input string.

        Returns:
            str: A snake_cased string.

        Example:
            >>> to_snake_case("Hello World!")
            'hello_world'
        """
    return re.sub(r'[^a-z0-9]+', '_', str)

to_title_case(str)

Convert a string into Title Case.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str

A title-cased string.

Example

to_title_case("hello world") 'Hello World'

Source code in pystringtoolkit/cases.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def to_title_case(str):
    """
        Convert a string into ``Title Case``.

        Args:
            text (str): The input string.

        Returns:
            str: A title-cased string.

        Example:
            >>> to_title_case("hello world")
            'Hello World'
        """
    return str.title()

to_upper_case(str)

Convert a string to uppercase.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

Uppercased version of the string.

Example

to_upper_case("hello") 'HELLO'

Source code in pystringtoolkit/cases.py
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def to_upper_case(str:str)->str:
    """
    Convert a string to uppercase.

    Args:
        text (str): The input string.

    Returns:
        str: Uppercased version of the string.

    Example:
        >>> to_upper_case("hello")
        'HELLO'
    """
    return str.upper()

invert_cases(str)

Invert the case of each character in a string. Lowercase characters become uppercase, and uppercase characters become lowercase. Non-alphabetic characters (like numbers and symbols) remain unchanged.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

A string with inverted letter cases.

Example

invert_cases("Hello World 123") 'hELLO wORLD 123'

Source code in pystringtoolkit/case_conversion.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def invert_cases(str:str)->str:
    """
       Invert the case of each character in a string.
       Lowercase characters become uppercase, and uppercase characters become lowercase.
       Non-alphabetic characters (like numbers and symbols) remain unchanged.

       Args:
           text (str): The input string.

       Returns:
           str: A string with inverted letter cases.

       Example:
           >>> invert_cases("Hello World 123")
           'hELLO wORLD 123'
       """
    inverted = []
    for char in str:
        if char.islower():
            inverted.append(char.upper())
        elif char.isupper():
            inverted.append(char.lower())
        else:
            inverted.append(char) #This is for the case of the numericals part
    return ''.join(inverted)

Cleaners

contains_only_alpha(str)

Check if a string contains only alphabetic characters and spaces.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
bool bool

True if the string contains only letters and spaces, False otherwise.

Example

contains_only_alpha("Hello World") True contains_only_alpha("Hello123") False

Source code in pystringtoolkit/cleaners.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def contains_only_alpha(str:str)->bool:
    """
        Check if a string contains only alphabetic characters and spaces.

        Args:
            text (str): The input string.

        Returns:
            bool: True if the string contains only letters and spaces, False otherwise.

        Example:
            >>> contains_only_alpha("Hello World")
            True
            >>> contains_only_alpha("Hello123")
            False
        """
    return bool(re.fullmatch(r'[A-Za-z\s]+',str))

remove_consonants(text)

Remove all consonants from a string, keeping only vowels and non-alphabetic characters.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

A string containing only vowels and non-alphabetic characters.

Example

remove_consonants("Hello World") 'eo o'

Source code in pystringtoolkit/cleaners.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def remove_consonants(text: str) -> str:
    """
    Remove all consonants from a string, keeping only vowels and non-alphabetic characters.

    Args:
        text (str): The input string.

    Returns:
        str: A string containing only vowels and non-alphabetic characters.

    Example:
        >>> remove_consonants("Hello World")
        'eo o'
    """
    vowels = "aeiouAEIOU"
    return ''.join(c for c in text if not c.isalpha() or c in vowels)

remove_extra_spaces(str)

Remove leading and trailing spaces from a string.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

The string without extra spaces at the beginning and end.

Example

remove_extra_spaces(" Hello World ") 'Hello World'

Source code in pystringtoolkit/cleaners.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def remove_extra_spaces(str:str)->str:
    """
        Remove leading and trailing spaces from a string.

        Args:
            text (str): The input string.

        Returns:
            str: The string without extra spaces at the beginning and end.

        Example:
            >>> remove_extra_spaces("   Hello World   ")
            'Hello World'
        """
    return str.strip()

remove_punctuation(str)

Remove all punctuation from a string, keeping only alphanumeric characters and whitespace.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

The string with punctuation removed.

Example

remove_punctuation("Hello, World!") 'Hello World'

Source code in pystringtoolkit/cleaners.py
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def remove_punctuation(str:str)->str:
    """
        Remove all punctuation from a string, keeping only alphanumeric characters and whitespace.

        Args:
            text (str): The input string.

        Returns:
            str: The string with punctuation removed.

        Example:
            >>> remove_punctuation("Hello, World!")
            'Hello World'
        """
    return re.sub(r'[^\w\s]','',str)

remove_vowels(text)

Remove all vowels from a string.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

A string with all vowels removed.

Example

remove_vowels("Hello World") 'Hll Wrld'

Source code in pystringtoolkit/cleaners.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def remove_vowels(text: str) -> str:
    """
    Remove all vowels from a string.

    Args:
        text (str): The input string.

    Returns:
        str: A string with all vowels removed.

    Example:
        >>> remove_vowels("Hello World")
        'Hll Wrld'
    """
    vowels = "aeiouAEIOU"
    return ''.join(c for c in text if c not in vowels)

remove_whitespaces(str)

Remove all whitespace characters from a string (spaces, tabs, newlines).

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

The string without any whitespace.

Example

remove_whitespaces("Hello World") 'HelloWorld'

Source code in pystringtoolkit/cleaners.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def remove_whitespaces(str:str)->str:
    """
       Remove all whitespace characters from a string (spaces, tabs, newlines).

       Args:
           text (str): The input string.

       Returns:
           str: The string without any whitespace.

       Example:
           >>> remove_whitespaces("Hello World")
           'HelloWorld'
       """
    return re.sub(r'[\s]','',str)

strip_html_tags(text)

Remove HTML tags from a given string.

Parameters:

Name Type Description Default
text str

The input string containing HTML.

required

Returns:

Name Type Description
str str

The cleaned string without HTML tags.

Source code in pystringtoolkit/cleaners.py
123
124
125
126
127
128
129
130
131
132
133
134
def strip_html_tags(text: str) -> str:
    """
    Remove HTML tags from a given string.

    Args:
        text (str): The input string containing HTML.

    Returns:
        str: The cleaned string without HTML tags.
    """
    clean = re.compile(r'<.*?>')
    return re.sub(clean, '', text)

truncate(str, length)

Truncate a string to a given length and append an ellipsis ("..."). If the string is shorter than or equal to the given length, it is returned unchanged.

Parameters:

Name Type Description Default
text str

The input string.

required
length int

The maximum length of the truncated string.

required

Returns:

Name Type Description
str str

The truncated string with ellipsis if necessary.

Example

truncate("Hello World", 5) 'Hello...'

Source code in pystringtoolkit/cleaners.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def truncate(str,length:str)->str:
    """
        Truncate a string to a given length and append an ellipsis ("...").
        If the string is shorter than or equal to the given length, it is returned unchanged.

        Args:
            text (str): The input string.
            length (int): The maximum length of the truncated string.

        Returns:
            str: The truncated string with ellipsis if necessary.

        Example:
            >>> truncate("Hello World", 5)
            'Hello...'
        """
    return str[:length] + '...'

Validators

are_anagrams(text1, text2)

Check if two strings are anagrams of each other (contain the same letters in a different order), ignoring case and spaces.

Parameters:

Name Type Description Default
text1 str

The first input string.

required
text2 str

The second input string.

required

Returns:

Name Type Description
bool bool

True if the strings are anagrams, False otherwise.

Example

are_anagrams("Listen", "Silent") True are_anagrams("Hello", "World") False

Source code in pystringtoolkit/validators.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def are_anagrams(text1: str, text2: str) -> bool:
    """
    Check if two strings are anagrams of each other (contain the same letters in a different order), ignoring case and spaces.

    Args:
        text1 (str): The first input string.
        text2 (str): The second input string.

    Returns:
        bool: True if the strings are anagrams, False otherwise.

    Example:
        >>> are_anagrams("Listen", "Silent")
        True
        >>> are_anagrams("Hello", "World")
        False
    """
    from collections import Counter
    return Counter(text1.lower().replace(" ", "")) == Counter(text2.lower().replace(" ", ""))

is_email(text)

Validate whether a string is a valid email address.

Uses a simple regex to check common email formats.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
bool bool

True if the input is a valid email address, False otherwise.

Example

is_email("test@example.com") True is_email("not-an-email") False

Source code in pystringtoolkit/validators.py
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def is_email(text:str)->bool:
    """
    Validate whether a string is a valid email address.

    Uses a simple regex to check common email formats.

    Args:
        text (str): The input string.

    Returns:
        bool: True if the input is a valid email address, False otherwise.

    Example:
        >>> is_email("test@example.com")
        True
        >>> is_email("not-an-email")
        False
    """
    if not text:
        return False

    pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
    return re.match(pattern, text) is not None

is_numeric(string)

Check if a value can be interpreted as a numeric value.

Parameters:

Name Type Description Default
string str | int | float

The value to check (can be string, int, float, or other types)

required

Returns:

Name Type Description
bool bool

True if the value is numeric, False otherwise

Examples:

>>> is_numeric("123")
True
>>> is_numeric("12.34")
True
>>> is_numeric("1e5")
True
>>> is_numeric("abc")
False
Source code in pystringtoolkit/validators.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def is_numeric(string:str|int|float)->bool:
    """
    Check if a value can be interpreted as a numeric value.

    Args:
        string: The value to check (can be string, int, float, or other types)

    Returns:
        bool: True if the value is numeric, False otherwise

    Examples:
        >>> is_numeric("123")
        True
        >>> is_numeric("12.34")
        True
        >>> is_numeric("1e5")
        True
        >>> is_numeric("abc")
        False
    """

is_palindrome(text)

Check if a string is a palindrome (reads the same forwards and backwards), ignoring case and non-alphanumeric characters.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
bool bool

True if the string is a palindrome, False otherwise.

Example

is_palindrome("A man, a plan, a canal, Panama") True is_palindrome("Hello") False

Source code in pystringtoolkit/validators.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def is_palindrome(text: str) -> bool:
    """
    Check if a string is a palindrome (reads the same forwards and backwards), ignoring case and non-alphanumeric characters.

    Args:
        text (str): The input string.

    Returns:
        bool: True if the string is a palindrome, False otherwise.

    Example:
        >>> is_palindrome("A man, a plan, a canal, Panama")
        True
        >>> is_palindrome("Hello")
        False
    """
    cleaned = ''.join(c.lower() for c in text if c.isalnum())
    return cleaned == cleaned[::-1]

isalpha(s)

Check if a string contains only alphabetic characters (A–Z, a–z).

Parameters:

Name Type Description Default
s str

The input string.

required

Returns:

Name Type Description
bool bool

True if the string contains only alphabetic characters, False otherwise.

Example

isalpha("Hello") True isalpha("Hello123") False

Source code in pystringtoolkit/validators.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def isalpha(s:str)->bool:
    """
        Check if a string contains only alphabetic characters (A–Z, a–z).

        Args:
            s (str): The input string.

        Returns:
            bool: True if the string contains only alphabetic characters, False otherwise.

        Example:
            >>> isalpha("Hello")
            True
            >>> isalpha("Hello123")
            False
    """
    return re.fullmatch(r"[A-Za-z]+", s) is not None

Generators

random_string(length)

Generate a random alphanumeric string of a given length.

Parameters:

Name Type Description Default
length int

The length of the string to generate.

required

Returns:

Name Type Description
str str

A randomly generated string containing letters and digits.

Example

random_string(8) 'aB3kLm9X'

Source code in pystringtoolkit/generators.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def random_string(length:int)->str:
    """
        Generate a random alphanumeric string of a given length.

        Args:
            length (int): The length of the string to generate.

        Returns:
            str: A randomly generated string containing letters and digits.

        Example:
            >>> random_string(8)
            'aB3kLm9X'
        """
    str=''.join(random.choices(string.ascii_letters+string.digits,k=length))
    return str

reverse_string(text)

Reverse the given string.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

The reversed string.

Example

reverse_string("Hello") 'olleH'

Source code in pystringtoolkit/generators.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def reverse_string(text: str) -> str:
    """
    Reverse the given string.

    Args:
        text (str): The input string.

    Returns:
        str: The reversed string.

    Example:
        >>> reverse_string("Hello")
        'olleH'
    """
    return text[::-1]

slugify(str)

Convert a string into a slug by lowercasing, trimming, and replacing spaces with hyphens.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
str str

A slugified version of the string.

Example

slugify("Hello World Example")

Source code in pystringtoolkit/generators.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def slugify(str:str)->str:
    """
        Convert a string into a slug by lowercasing, trimming, and replacing spaces with hyphens.

        Args:
            text (str): The input string.

        Returns:
            str: A slugified version of the string.

        Example:
            >>> slugify("Hello World Example")
    """
    str=str.lower().strip()
    return re.sub(r'\s+','-',str)

Counters

char_frequency(text)

Count the frequency of each character in a string.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
dict dict

A dictionary with characters as keys and their counts as values.

Example

char_frequency("hello") {'h': 1, 'e': 1, 'l': 2, 'o': 1}

Source code in pystringtoolkit/counting.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def char_frequency(text: str) -> dict:
    """
    Count the frequency of each character in a string.

    Args:
        text (str): The input string.

    Returns:
        dict: A dictionary with characters as keys and their counts as values.

    Example:
        >>> char_frequency("hello")
        {'h': 1, 'e': 1, 'l': 2, 'o': 1}
    """
    freq = {}
    for char in text:
        freq[char] = freq.get(char, 0) + 1
    return freq

most_common_char(text)

Find the most common character in a string.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Type Description
str | None

str | None: The character that appears most frequently, or None if string is empty.

Example

most_common_char("hello") 'l'

Source code in pystringtoolkit/counting.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def most_common_char(text: str) -> str | None:
    """
    Find the most common character in a string.

    Args:
        text (str): The input string.

    Returns:
        str | None: The character that appears most frequently, or None if string is empty.

    Example:
        >>> most_common_char("hello")
        'l'
    """
    if not text:
        return None
    freq = char_frequency(text)
    return max(freq, key=freq.get)

unique_words(text)

Return a list of unique words from the string (case-insensitive), preserving order.

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
list list

A list of unique words.

Example

unique_words("Hello hello world") ['hello', 'world']

Source code in pystringtoolkit/counting.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def unique_words(text: str) -> list:
    """
    Return a list of unique words from the string (case-insensitive), preserving order.

    Args:
        text (str): The input string.

    Returns:
        list: A list of unique words.

    Example:
        >>> unique_words("Hello hello world")
        ['hello', 'world']
    """
    words = text.lower().split()
    return list(dict.fromkeys(words))

word_count(text)

Count the occurrences of each word in a string (case-insensitive).

Parameters:

Name Type Description Default
text str

The input string.

required

Returns:

Name Type Description
dict dict

A dictionary with words as keys and their counts as values.

Example

word_count("Hello hello world") {'hello': 2, 'world': 1}

Source code in pystringtoolkit/counting.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def word_count(text: str) -> dict:
    """
    Count the occurrences of each word in a string (case-insensitive).

    Args:
        text (str): The input string.

    Returns:
        dict: A dictionary with words as keys and their counts as values.

    Example:
        >>> word_count("Hello hello world")
        {'hello': 2, 'world': 1}
    """
    words = text.lower().split()
    freq = {}
    for word in words:
        freq[word] = freq.get(word, 0) + 1
    return freq