Skip to content

Strings

toolbox_python.strings ๐Ÿ”—

Summary

The strings module is for manipulating and checking certain string objects.

str_replace ๐Ÿ”—

str_replace(
    old_string: str,
    replace_chars: str = string.punctuation
    + string.whitespace,
    replace_with: str = "",
) -> str

Summary

Replace the characters with a given string.

Details

Similar to the Python str.replace() method, but provides more customisation through the use of the re package.

Parameters:

Name Type Description Default
old_string str

The old string to be replaced.

required
replace_chars str

The characters that need replacing.
Defaults to string.punctuation + string.whitespace.

punctuation + whitespace
replace_with str

The value to replace the characters with.
Defaults to "".

''

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
str

The new formatted string.

Examples
Set up
1
2
3
>>> from toolbox_python.strings import str_replace
>>> long_string = "This long string"
>>> complex_sentence = "Because my pizza was cold, I put it in the microwave."

Example 1: Replace all spaces (` `) with underscore (`_`)
1
>>> print(str_replace(long_string, " ", "_"))
Terminal
"This_long_string"

Conclusion: Successful conversion.

Example 2: Remove all punctuation and white space
1
>>> print(str_replace(complex_sentence))
Terminal
"BecausemylunchwascoldIputitinthemicrowave"

Conclusion: Successful conversion.

Example 3: Invalid `old_string` input
1
>>> print(str_replace(123))
Terminal
TypeError: ...

Conclusion: Invalid input.

Note: The same error will occur if replace_chars or replace_with are not of type str.

Credit

Full credit goes to:
https://stackoverflow.com/questions/23996118/replace-special-characters-in-a-string-python#answer-23996414

See Also
Source code in src/toolbox_python/strings.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
@typechecked
def str_replace(
    old_string: str,
    replace_chars: str = string.punctuation + string.whitespace,
    replace_with: str = "",
) -> str:
    """
    !!! note "Summary"
        Replace the characters with a given string.

    ???+ abstract "Details"
        Similar to the Python `#!py str.replace()` method, but provides more customisation through the use of the [`re`](https://docs.python.org/3/library/re.html) package.

    Params:
        old_string (str):
            The old string to be replaced.
        replace_chars (str, optional):
            The characters that need replacing.<br>
            Defaults to `#!py string.punctuation + string.whitespace`.
        replace_with (str, optional):
            The value to replace the characters with.<br>
            Defaults to `""`.

    Raises:
        TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (str):
            The new formatted string.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> from toolbox_python.strings import str_replace
        >>> long_string = "This long string"
        >>> complex_sentence = "Because my pizza was cold, I put it in the microwave."
        ```

        ```{.py .python linenums="1" title="Example 1: Replace all spaces (` `) with underscore (`_`)"}
        >>> print(str_replace(long_string, " ", "_"))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        "This_long_string"
        ```
        !!! success "Conclusion: Successful conversion."
        </div>

        ```{.py .python linenums="1" title="Example 2: Remove all punctuation and white space"}
        >>> print(str_replace(complex_sentence))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        "BecausemylunchwascoldIputitinthemicrowave"
        ```
        !!! success "Conclusion: Successful conversion."
        </div>

        ```{.py .python linenums="1" title="Example 3: Invalid `old_string` input"}
        >>> print(str_replace(123))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        TypeError: ...
        ```
        !!! failure "Conclusion: Invalid input."
        !!! observation "Note: The same error will occur if `replace_chars` or `replace_with` are not of type `str`."
        </div>

    ??? success "Credit"
        Full credit goes to:<br>
        https://stackoverflow.com/questions/23996118/replace-special-characters-in-a-string-python#answer-23996414

    ??? tip "See Also"
        - [`re`](https://docs.python.org/3/library/re.html)
    """
    chars: str = re.escape(replace_chars)
    return re.sub(rf"[{chars}]", replace_with, old_string)

str_contains ๐Ÿ”—

str_contains(check_string: str, sub_string: str) -> bool

Summary

Check whether one string contains another string.

Details

This is a super simple one-line function.

Example
1
return True if sub_string in check_string else False

Parameters:

Name Type Description Default
check_string str

The main string to check.

required
sub_string str

The substring to check.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
bool

True if sub_string in check_string

Examples
Set up
1
2
>>> from toolbox_python.strings import str_contains
>>> long_string = "This long string"

Example 1: String is contained
1
>>> print(str_contains(long_string, "long"))
Terminal
True

Conclusion: long_string contains "long".

Example 2: String is not contained
1
>>> print(str_contains(long_string, "short"))
Terminal
False

Conclusion: long_string does not contain "short".

Example 3: Invalid `check_string` input
1
>>> print(str_contains(123, "short"))
Terminal
TypeError: ...

Conclusion: Invalid input.

Note: The same error will occur if sub_string is not of type str.

See Also
Source code in src/toolbox_python/strings.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@typechecked
def str_contains(check_string: str, sub_string: str) -> bool:
    """
    !!! note "Summary"
        Check whether one string contains another string.

    ???+ abstract "Details"
        This is a super simple one-line function.

        ```py linenums="1" title="Example"
        return True if sub_string in check_string else False
        ```

    Params:
        check_string (str):
            The main string to check.
        sub_string (str):
            The substring to check.

    Raises:
        TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (bool):
            `#!py True` if `#!py sub_string` in `#!py check_string`

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> from toolbox_python.strings import str_contains
        >>> long_string = "This long string"
        ```

        ```{.py .python linenums="1" title="Example 1: String is contained"}
        >>> print(str_contains(long_string, "long"))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: `#!py long_string` contains `#!py "long"`."
        </div>

        ```{.py .python linenums="1" title="Example 2: String is not contained"}
        >>> print(str_contains(long_string, "short"))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! success "Conclusion: `#!py long_string` does not contain `#!py "short"`."
        </div>

        ```{.py .python linenums="1" title="Example 3: Invalid `check_string` input"}
        >>> print(str_contains(123, "short"))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        TypeError: ...
        ```
        !!! failure "Conclusion: Invalid input."
        !!! observation "Note: The same error will occur if `sub_string` is not of type `str`."
        </div>

    ??? tip "See Also"
        - [`str_contains_any()`][toolbox_python.strings.str_contains_any]
        - [`str_contains_all()`][toolbox_python.strings.str_contains_all]
    """
    return sub_string in check_string

str_contains_any ๐Ÿ”—

str_contains_any(
    check_string: str, sub_strings: str_list_tuple
) -> bool

Summary

Check whether any one of a number of strings are contained within a main string.

Parameters:

Name Type Description Default
check_string str

The main string to check.

required
sub_strings str_list_tuple

The collection of substrings to check.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
bool

True if any of the strings in sub_strings are contained within check_string.

Examples
Set up
1
2
>>> from toolbox_python.strings import str_contains_any
>>> long_string = "This long string"

Example 1: Contains any
1
>>> print(str_contains_any(long_string, ["long", "short"]))
Terminal
True

Conclusion: long_string contains either "long" or "short".

Example 2: Contains none
1
>>> print(str_contains_any(long_string, ["this", "that"]))
Terminal
False

Conclusion: long_string contains neither "this" nor "that".

Example 3: Invalid `check_string` input
1
>>> print(str_contains_any(123, ["short", "long"]))
Terminal
TypeError: ...

Conclusion: Invalid input.

Note: The same error will occur if any of the elements in sub_strings are not of type str.

See Also
Source code in src/toolbox_python/strings.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
@typechecked
def str_contains_any(
    check_string: str,
    sub_strings: str_list_tuple,
) -> bool:
    """
    !!! note "Summary"
        Check whether any one of a number of strings are contained within a main string.

    Params:
        check_string (str):
            The main string to check.
        sub_strings (str_list_tuple):
            The collection of substrings to check.

    Raises:
        TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (bool):
            `#!py True` if `#!py any` of the strings in `#!py sub_strings` are contained within `#!py check_string`.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> from toolbox_python.strings import str_contains_any
        >>> long_string = "This long string"
        ```

        ```{.py .python linenums="1" title="Example 1: Contains any"}
        >>> print(str_contains_any(long_string, ["long", "short"]))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: `#!py long_string` contains either `#!py "long"` or `#!py "short"`."
        </div>

        ```{.py .python linenums="1" title="Example 2: Contains none"}
        >>> print(str_contains_any(long_string, ["this", "that"]))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! success "Conclusion: `#!py long_string` contains neither `#!py "this"` nor `#!py "that"`."
        </div>

        ```{.py .python linenums="1" title="Example 3: Invalid `check_string` input"}
        >>> print(str_contains_any(123, ["short", "long"]))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        TypeError: ...
        ```
        !!! failure "Conclusion: Invalid input."
        !!! observation "Note: The same error will occur if any of the elements in `sub_strings` are not of type `str`."
        </div>

    ??? tip "See Also"
        - [`str_contains()`][toolbox_python.strings.str_contains]
        - [`str_contains_all()`][toolbox_python.strings.str_contains_all]
    """
    return any(
        str_contains(
            check_string=check_string,
            sub_string=sub_string,
        )
        for sub_string in sub_strings
    )

str_contains_all ๐Ÿ”—

str_contains_all(
    check_string: str, sub_strings: str_list_tuple
) -> bool

Summary

Check to ensure that all sub-strings are contained within a main string.

Parameters:

Name Type Description Default
check_string str

The main string to check.

required
sub_strings str_list_tuple

The collection of substrings to check.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
bool

True if all of the strings in sub_strings are contained within check_string.

Examples
Set up
1
2
>>> from toolbox_python.strings import str_contains_all
>>> long_string = "This long string"

Example 1: Contains all
1
>>> print(str_contains_all(long_string, ["long", "string"]))
Terminal
True

Conclusion: long_string contains both "long" and "string".

Example 2: Contains some
1
>>> print(str_contains_all(long_string, ["long", "something"]))
Terminal
False

Conclusion: long_string contains "long" but not "something".

Example 3: Contains none
1
>>> print(str_contains_all(long_string, ["this", "that"]))
Terminal
False

Conclusion: long_string contains neither "this" nor "that".

Example 4: Invalid `check_string` input
1
>>> print(str_contains_all(123, ["short", "long"]))
Terminal
TypeError: ...

Conclusion: Invalid input.

Note: The same error will occur if any of the elements in sub_strings are not of type str.

See Also
Source code in src/toolbox_python/strings.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
@typechecked
def str_contains_all(
    check_string: str,
    sub_strings: str_list_tuple,
) -> bool:
    """
    !!! note "Summary"
        Check to ensure that all sub-strings are contained within a main string.

    Params:
        check_string (str):
            The main string to check.
        sub_strings (str_list_tuple):
            The collection of substrings to check.

    Raises:
        TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (bool):
            `#!py True` if `#!py all` of the strings in `#!py sub_strings` are contained within `#!py check_string`.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> from toolbox_python.strings import str_contains_all
        >>> long_string = "This long string"
        ```

        ```{.py .python linenums="1" title="Example 1: Contains all"}
        >>> print(str_contains_all(long_string, ["long", "string"]))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        ```
        !!! success "Conclusion: `#!py long_string` contains both `#!py "long"` and `#!py "string"`."
        </div>

        ```{.py .python linenums="1" title="Example 2: Contains some"}
        >>> print(str_contains_all(long_string, ["long", "something"]))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: `#!py long_string` contains `#!py "long"` but not `#!py "something"`."
        </div>

        ```{.py .python linenums="1" title="Example 3: Contains none"}
        >>> print(str_contains_all(long_string, ["this", "that"]))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        ```
        !!! failure "Conclusion: `#!py long_string` contains neither `#!py "this"` nor `#!py "that"`."
        </div>

        ```{.py .python linenums="1" title="Example 4: Invalid `check_string` input"}
        >>> print(str_contains_all(123, ["short", "long"]))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        TypeError: ...
        ```
        !!! failure "Conclusion: Invalid input."
        !!! observation "Note: The same error will occur if any of the elements in `sub_strings` are not of type `str`."
        </div>

    ??? tip "See Also"
        - [`str_contains()`][toolbox_python.strings.str_contains]
        - [`str_contains_any()`][toolbox_python.strings.str_contains_any]
    """
    return all(
        str_contains(
            check_string=check_string,
            sub_string=sub_string,
        )
        for sub_string in sub_strings
    )

str_separate_number_chars ๐Ÿ”—

str_separate_number_chars(text: str) -> str_list

Summary

Take in a string that contains both numbers and letters, and output a list of strings, separated to have each element containing either entirely number or entirely letters.

Details

Uses regex (re.split()) to perform the actual splitting.
Note, it will preserve special characters & punctuation, but it will not preserve whitespaces.

Parameters:

Name Type Description Default
text str

The string to split.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

Returns:

Type Description
str_list

The updated list, with each element of the list containing either entirely characters or entirely numbers.

Examples
Set up
1
2
3
>>> from toolbox_python.strings import str_contains_all
>>> simple_string = "-12.1grams"
>>> complex_string = "abcd2343 abw34324 abc3243-23A 123"

Example 1: Simple split
1
>>> print(str_separate_number_chars(simple_string))
Terminal
["-12.1", "grams"]

Conclusion: Successful split.

Example 2: Complex split
1
>>> print(str_separate_number_chars(complex_string))
Terminal
[
    "abcd",
    "2343",
    "abw",
    "34324",
    "abc",
    "3243",
    "-23",
    "A",
    "123",
]

Conclusion: Successful split.

Example 3: `text` does not contain any numbers
1
>>> print(str_separate_number_chars("abcd"))
Terminal
["abcd"]

Conclusion: No numbers in text, so returns a single-element long list.

Example 4: Invalid `text` input
1
>>> print(str_separate_number_chars(123))
Terminal
TypeError: ...

Conclusion: Invalid input.

Credit

Full credit goes to:
https://stackoverflow.com/questions/3340081/product-code-looks-like-abcd2343-how-to-split-by-letters-and-numbers#answer-63362709.

See Also
Source code in src/toolbox_python/strings.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
@typechecked
def str_separate_number_chars(text: str) -> str_list:
    """
    !!! note "Summary"
        Take in a string that contains both numbers and letters, and output a list of strings, separated to have each element containing either entirely number or entirely letters.

    ???+ abstract "Details"
        Uses regex ([`re.split()`](https://docs.python.org/3/library/re.html#re.split)) to perform the actual splitting.<br>
        Note, it _will_ preserve special characters & punctuation, but it _will not_ preserve whitespaces.

    Params:
        text (str):
            The string to split.

    Raises:
        TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.

    Returns:
        (str_list):
            The updated list, with each element of the list containing either entirely characters or entirely numbers.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> from toolbox_python.strings import str_contains_all
        >>> simple_string = "-12.1grams"
        >>> complex_string = "abcd2343 abw34324 abc3243-23A 123"
        ```

        ```{.py .python linenums="1" title="Example 1: Simple split"}
        >>> print(str_separate_number_chars(simple_string))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        ["-12.1", "grams"]
        ```
        !!! success "Conclusion: Successful split."
        </div>

        ```{.py .python linenums="1" title="Example 2: Complex split"}
        >>> print(str_separate_number_chars(complex_string))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        [
            "abcd",
            "2343",
            "abw",
            "34324",
            "abc",
            "3243",
            "-23",
            "A",
            "123",
        ]
        ```
        !!! success "Conclusion: Successful split."
        </div>

        ```{.py .python linenums="1" title="Example 3: `text` does not contain any numbers"}
        >>> print(str_separate_number_chars("abcd"))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        ["abcd"]
        ```
        !!! success "Conclusion: No numbers in `#!py text`, so returns a single-element long list."
        </div>

        ```{.py .python linenums="1" title="Example 4: Invalid `text` input"}
        >>> print(str_separate_number_chars(123))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        TypeError: ...
        ```
        !!! failure "Conclusion: Invalid input."
        </div>

    ??? success "Credit"
        Full credit goes to:<br>
        https://stackoverflow.com/questions/3340081/product-code-looks-like-abcd2343-how-to-split-by-letters-and-numbers#answer-63362709.

    ??? tip "See Also"
        - [`re`](https://docs.python.org/3/library/re.html)
    """
    res = re.split(r"([-+]?\d+\.\d+)|([-+]?\d+)", text.strip())
    return [r.strip() for r in res if r is not None and r.strip() != ""]