string_operations¶
shortfx.fxString.string_operations
¶
String Operations and Manipulation Functions.
This module provides a comprehensive set of functions for string manipulation and operations. It includes utilities for extracting, splitting, joining, transforming, and analyzing strings in various ways.
Key Features: - Character and word counting - Substring extraction and manipulation - Position finding and pattern matching - String splitting and joining - Number extraction from strings - Content extraction between delimiters - String cleaning and formatting - Word manipulation and reordering
Functions¶
abbreviate(text: str, separator: str = '') -> str
¶
Generates an abbreviation (initials/acronym) from a text string.
Takes the first letter of each word and joins them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
separator
|
str
|
Character placed between initials. |
''
|
Returns:
| Type | Description |
|---|---|
str
|
The abbreviation string in uppercase. |
Example
abbreviate("World Health Organization") 'WHO' abbreviate("artificial intelligence", separator=".") 'A.I.'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
add_quotes(text: Optional[str], quote_type: str = "'") -> Optional[str]
¶
Adds single or double quotes to the beginning and end of a string.
This function wraps the input string with the specified quote character. It performs input validation and defaults to single quotes if an invalid quote type is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The string to be quoted. Can be None. |
required |
quote_type
|
str
|
The type of quote to use. Must be either "'" (single) or '"' (double). Defaults to single quote. |
"'"
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The quoted string, or None if the input was None. Non-string inputs are converted to strings before quoting. |
Example of use
add_quotes("hello world") "'hello world'" add_quotes("Python is great", '"') '"Python is great"' add_quotes("text with 'quotes'", '"') '"text with 'quotes'"' add_quotes(None) None add_quotes(123) "'123'"
Cost
O(n) where n is the length of the input string.
Source code in shortfx/fxString/string_operations.py
ascii_from_char(character: str) -> int
¶
Devuelve el valor entero (código Unicode/ASCII) del primer carácter de una cadena.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
str
|
La cadena de la que se obtendrá el valor entero del primer carácter. Solo se considera el primer carácter si la cadena tiene más de uno. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
El valor entero correspondiente al carácter. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si la entrada no es una cadena. |
ValueError
|
Si la cadena de entrada está vacía. |
Ejemplos de uso
ascii_from_char("A") 65 ascii_from_char("a") 97 ascii_from_char(" ") 32 ascii_from_char("€") # Carácter Unicode 8364 ascii_from_char("Python") # Solo toma el primer carácter 'P' 80
Cost: O(1), constant time operation
Source code in shortfx/fxString/string_operations.py
caesar_cipher(text: str, shift: int) -> str
¶
Apply Caesar cipher with the given shift (positive = right).
Only shifts ASCII letters; other characters are unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
shift
|
int
|
Number of positions to shift. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Ciphered string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If types are incorrect. |
Usage Example
caesar_cipher('abc', 3) 'def'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
camel_to_snake(text: str) -> str
¶
Convert camelCase or PascalCase to snake_case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
camelCase or PascalCase string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
snake_case string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
camel_to_snake('helloWorld') 'hello_world'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
center_string(text: str, width: int, fill_char: str = ' ') -> str
¶
Centers a string within a given width using a fill character.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The string to center. |
required |
width
|
int
|
The total width of the resulting string. |
required |
fill_char
|
str
|
The padding character. |
' '
|
Returns:
| Type | Description |
|---|---|
str
|
The centered string, or the original if it is already wider. |
Example
center_string("hello", 11, "-") '---hello---' center_string("hi", 6) ' hi '
Complexity: O(width)
Source code in shortfx/fxString/string_operations.py
char_from_ascii(integer_code: int) -> str
¶
Devuelve el carácter correspondiente a un valor entero (código Unicode/ASCII).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
integer_code
|
int
|
El valor entero (código Unicode/ASCII) del carácter deseado. Debe ser un valor Unicode válido (0 a 1,114,111). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
El carácter correspondiente al valor entero. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si la entrada no es un entero. |
ValueError
|
Si el entero está fuera del rango de los códigos Unicode válidos. |
Ejemplos de uso
char_from_ascii(65) 'A' char_from_ascii(97) 'a' char_from_ascii(32) ' ' char_from_ascii(8364) # Carácter Euro '€' char_from_ascii(100000) # Un carácter Unicode menos común '𖠀'
Source code in shortfx/fxString/string_operations.py
chunk_string(text: str, size: int) -> list
¶
Split text into chunks of size characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
size
|
int
|
Chunk width (> 0). |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of string chunks. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If types are incorrect. |
ValueError
|
If size ≤ 0. |
Usage Example
chunk_string('abcdefgh', 3) ['abc', 'def', 'gh']
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
clean_non_printable(text: str) -> str
¶
Removes all non-printable characters (ASCII 0-31) from a string.
Equivalent to Excel CLEAN function for fxString.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The string with non-printable characters removed. |
Example
clean_non_printable("Hello\x00World\n") 'HelloWorld'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
clean_nonprintable(text: str) -> str
¶
Remove all nonprintable characters (ASCII 0–31) from text.
Equivalent to the Excel CLEAN function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Text to clean. |
required |
Returns:
| Type | Description |
|---|---|
str
|
String with all control characters removed. |
Example
clean_nonprintable("Hello World") 'HelloWorld'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
collapse_whitespace(text: str) -> str
¶
Replace consecutive whitespace with a single space and strip edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
String with normalised whitespace. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
collapse_whitespace(' hello world ') 'hello world'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
cologne_phonetic(text: str) -> str
¶
Compute the Kölner Phonetik (Cologne Phonetic) code.
Description
A phonetic algorithm optimised for the German language. Maps characters to digit codes based on context (preceding and following characters).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to encode. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The Cologne phonetic code as a digit string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If text is empty after cleaning. |
Usage Example
cologne_phonetic("Müller") '657' cologne_phonetic("Schmidt") '862'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 | |
common_substring(string1: str, string2: str, min_longest_substring: int = 4) -> str
¶
Finds the longest common substring between two input strings, ignoring case, and ensures the substring is at least the length of the shortest word in either string.
This function uses a dynamic programming approach to determine the longest
contiguous sequence of characters that is common to both string1 and string2.
The comparison is case-insensitive. If no common substring is found, or if
the found substring is shorter than the shortest word in either input string,
an empty string is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string1
|
str
|
The first input string. |
required |
string2
|
str
|
The second input string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The longest common substring that meets the minimum length requirement. |
str
|
Returns an empty string if no common substring exists, if either input string |
str
|
is empty, or if the found substring is shorter than the shortest word. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either |
Example of use
common_substring("abcdef", "zbcdexy") "BCDE"
common_substring("Hello World", "world cup") "WORLD"
common_substring("apple", "banana") "" # 'a' is shorter than 'apple' or 'banana'
common_substring("test", "no match") ""
common_substring("", "abc") ""
common_substring("LongerExample", "a longer example phrase") "LONGEREXAMPLE" # "LONGER" is the common substring, but "LONGEREXAMPLE" is not the common string. It is not longer than "LongerExample" or "longer".
common_substring("test string", "another test phrase") "TEST"
Source code in shortfx/fxString/string_operations.py
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 | |
concatenate_strings(string1: str, string2: str) -> str
¶
Concatenates two strings into a single string.
This function combines two string inputs using the + operator. While
str.join() is more efficient for a list of many strings, the +
operator is perfectly clear and performant for just two strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string1
|
str
|
The first string. |
required |
string2
|
str
|
The second string. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The single concatenated string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either input is not a string. |
Example of use
first_name = "John" last_name = "Doe" full_name = concatenate_two_strings(first_name, last_name) 'JohnDoe'
Cost
The time complexity is O(N + M), where N and M are the lengths of the two input strings. The space complexity is O(N + M) to store the new resulting string.
Source code in shortfx/fxString/string_operations.py
constant_case(text: str) -> str
¶
Convert whitespace-separated text to CONSTANT_CASE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
CONSTANT_CASE string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
constant_case('Hello World') 'HELLO_WORLD'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
count_characters(input_string: str, target_char: str) -> int
¶
Counts the occurrences of a specific character within a string.
This function leverages the built-in str.count() method to efficiently
determine how many times a given character appears in the input string.
The comparison is case-sensitive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to search within. |
required |
target_char
|
str
|
The single character to count. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of times 'target_char' appears in 'input_string'. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'input_string' is not a string or 'target_char' is not a string. |
ValueError
|
If 'target_char' is an empty string or contains more than one character. |
Example
count_characters("hello world", "o") 2
count_characters("programming", "g") 2
count_characters("Banana", "a") 3
count_characters("Banana", "A") # Case-sensitive 0
count_characters("test", "x") 0
count_characters("", "a") 0
Source code in shortfx/fxString/string_operations.py
count_consonants(text: str, lang: str = 'en') -> int
¶
Counts the number of consonants in a text string.
Non-alphabetic characters are ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
lang
|
str
|
Language code ( |
'en'
|
Returns:
| Type | Description |
|---|---|
int
|
Number of consonant characters. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
count_consonants("Hello World") 7
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
count_lines(text: str) -> int
¶
Counts the number of lines in a text string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of lines (at least 1 for non-empty text, 0 for empty). |
Example
count_lines("line1\nline2\nline3") 3 count_lines("") 0
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
count_occurrences(text: str, sub: str) -> int
¶
Count non-overlapping occurrences of sub in text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
sub
|
str
|
Substring to count. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of occurrences. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If arguments are not strings. |
Usage Example
count_occurrences('banana', 'an') 2
Complexity: O(n·m)
Source code in shortfx/fxString/string_operations.py
count_syllables(text: str, lang: str = 'en') -> int
¶
Estimates the total number of syllables in a text.
Description
Uses a heuristic vowel-cluster approach for English and a vowel-group count for Spanish. Intended for readability metrics, not linguistic accuracy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
lang
|
str
|
Language code ( |
'en'
|
Returns:
| Type | Description |
|---|---|
int
|
Estimated syllable count (minimum 1 per word). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If lang is not |
Usage Example
count_syllables("beautiful day") 4
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 | |
count_vowels(text: str, lang: str = 'en') -> int
¶
Count vowels in a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Input text. |
required |
lang
|
str
|
Language code ( |
'en'
|
Returns:
| Type | Description |
|---|---|
int
|
Number of vowels found. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
count_vowels("Hello World") 3
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
count_words(input_string: str) -> int
¶
Counts the number of words in a given string.
This function splits the string by whitespace characters and returns
the total number of resulting words. It handles multiple spaces
between words and leading/trailing spaces correctly, as str.split()
by default splits by any whitespace and discards empty strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string whose words are to be counted. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The total number of words in the string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'input_string' is not a string. |
Example
count_words("Hello world") 2
count_words(" Leading and trailing spaces ") 4
count_words("SingleWord") 1
count_words("") 0
count_words(" ") # Only spaces 0
Cost: O(n), where n is the length of the input string
Source code in shortfx/fxString/string_operations.py
dedent_text(text: str) -> str
¶
Remove common leading whitespace from all lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Input text with indentation. |
required |
Returns:
| Type | Description |
|---|---|
str
|
De-indented text. |
Example
dedent_text(" hello\n world") 'hello\nworld'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
deduplicate_words(text: str) -> str
¶
Removes duplicate words from a text, preserving first occurrence order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Text with duplicates removed. |
Example
deduplicate_words("the cat and the dog and the bird") 'the cat and dog bird' deduplicate_words("hello hello hello") 'hello'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
distinct_split(text: str, separator: str = ';', *, strip_tokens: bool = True, case_sensitive: bool = True) -> str
¶
Split a delimited string, remove duplicate tokens, and re-join.
Combines str.split with first-occurrence deduplication in a single
pass. Useful for cleaning fields that accumulate repeated values
after concatenation (e.g. licence lists separated by ";"). Empty
tokens (or tokens that become empty after stripping) are silently
discarded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The delimited string to process. |
required |
separator
|
str
|
Delimiter used to split and re-join tokens. |
';'
|
strip_tokens
|
bool
|
If |
True
|
case_sensitive
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
str
|
A string with unique tokens joined by separator. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
distinct_split("Office365;PowerBI;Office365;Visio;PowerBI") 'Office365;PowerBI;Visio'
distinct_split("a ; b ; a ; c", separator=";") 'a;b;c'
distinct_split("Alpha;alpha;ALPHA", case_sensitive=False) 'Alpha'
distinct_split("x|y|x|z", separator="|") 'x|y|z'
distinct_split("one,,two,,one", separator=",") 'one,two'
Cost
O(n) where n is the length of text. Uses a single
iteration with a set for O(1) membership checks.
Source code in shortfx/fxString/string_operations.py
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 | |
distinct_words(input_string: str, case_sensitive: bool = False) -> list[str]
¶
Extracts all unique words from a string, with an option for case sensitivity.
This function first tokenizes the input string into words, considering only alphanumeric characters. It then returns a list of these words, ensuring each word appears only once. The comparison for distinctness can be configured to be case-sensitive or case-insensitive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string from which to extract distinct words. |
required |
case_sensitive
|
bool
|
If True, words like "Apple" and "apple" are considered distinct. If False (default), they are considered the same word. |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: A list of unique words found in the input string.
The words will be in the case they appeared in the original
string if |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'input_string' is not a string. |
Example
distinct_words("Hello world, hello Python!", case_sensitive=False) ['hello', 'world', 'python']
distinct_words("Apple, apple, Banana", case_sensitive=True) ['Apple', 'apple', 'Banana']
distinct_words("One two ONE three.", case_sensitive=False) ['one', 'two', 'three']
distinct_words("A B C a b c", case_sensitive=True) ['A', 'B', 'C', 'a', 'b', 'c']
distinct_words(" leading and trailing spaces ") ['leading', 'and', 'trailing', 'spaces']
distinct_words("No-punctuation_here,just words!") ['no', 'punctuation', 'here', 'just', 'words']
Source code in shortfx/fxString/string_operations.py
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 | |
double_metaphone(text: str) -> tuple
¶
Compute the Double Metaphone phonetic encoding.
Description
Produces a primary and alternate phonetic key. Handles Germanic, Celtic, Romance, and Slavic name origins better than the original Metaphone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to encode. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If text is empty after cleaning. |
Usage Example
double_metaphone("Smith") ('SM0', 'XMT') double_metaphone("Schmidt") ('XMT', 'SMT')
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 | |
erase_allspaces(text: Optional[str]) -> Optional[str]
¶
Removes all whitespace characters from the input string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with all spaces removed, or None if the input was None. Returns an empty string if the input was an empty string. |
Source code in shortfx/fxString/string_operations.py
erase_between_delimiters(text: Optional[str], delimiter_key: str) -> Optional[str]
¶
Removes text content that is enclosed between a specified pair of delimiters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string from which to remove content. Can be None. |
required |
delimiter_key
|
str
|
A key representing the type of delimiters to use. Supported: '/ /', '()', '[]', '{}', '<>', '""', "''", '$$' |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with content between delimiters removed, or None if the input was None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported delimiter key is provided. |
Example of use
erase_between_delimiters("hello(world)foo", "()") 'hellofoo' erase_between_delimiters("this /a comment/ is some code", "/ /") 'this is some code'
Source code in shortfx/fxString/string_operations.py
erase_digits(text: Optional[str]) -> Optional[str]
¶
Removes all digit characters from the input string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with digits removed, or None if the input was None. Returns an empty string if the input was an empty string. |
Source code in shortfx/fxString/string_operations.py
erase_lrspaces(text: Optional[str]) -> Optional[str]
¶
Removes leading and trailing whitespace from the input string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with leading/trailing spaces removed, or None if the input was None. Returns an empty string if the input was an empty string. |
Source code in shortfx/fxString/string_operations.py
erase_lspaces(text: Optional[str]) -> Optional[str]
¶
Removes leading (left) whitespace from the input string.
Equivalent to VBA's LTrim function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with leading spaces removed, or None if the input was None. |
Usage Example
erase_lspaces(" hello ") 'hello '
Cost: O(n), where n is the length of the text.
Source code in shortfx/fxString/string_operations.py
erase_rspaces(text: Optional[str]) -> Optional[str]
¶
Removes trailing (right) whitespace from the input string.
Equivalent to VBA's RTrim function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with trailing spaces removed, or None if the input was None. |
Usage Example
erase_rspaces(" hello ") ' hello'
Cost: O(n), where n is the length of the text.
Source code in shortfx/fxString/string_operations.py
erase_specialchar(text: str, allow_spaces: bool = True, allow_underscores: bool = False, additional_allowed_chars: str = '') -> str
¶
Limpia una cadena de texto eliminando caracteres especiales. Optimizada con patrones pre-compilados y técnicas de procesamiento eficientes.
La función convierte la cadena a mayúsculas, normaliza los acentos, y luego elimina todos los caracteres que no sean alfanuméricos, espacios (opcional), guiones bajos (opcional) o caracteres especificados adicionalmente.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
La cadena de texto a limpiar. |
required |
allow_spaces
|
bool
|
Si es True, permite espacios en blanco. Por defecto es True. |
True
|
allow_underscores
|
bool
|
Si es True, permite guiones bajos. Por defecto es False. |
False
|
additional_allowed_chars
|
str
|
Una cadena de caracteres adicionales que deben conservarse (ej. '.-_'). |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La cadena de texto limpia. |
Cost
O(n) where n is the length of the text. Optimized with list comprehension for accent removal and pre-compiled regex for whitespace normalization.
Source code in shortfx/fxString/string_operations.py
erase_symbol(p_iparse: str | None) -> str | None
¶
Removes a predefined set of common symbols from the input string, then applies a general special character cleaning and space normalization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_iparse
|
str | None
|
The input string. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The cleaned string, or None if input was None. |
Source code in shortfx/fxString/string_operations.py
extract_content_by_encloser_type(input_string: str, encloser_type: str) -> str
¶
Extracts the substring enclosed within a specific type of encloser
(e.g., parentheses, square brackets, curly braces, angle brackets,
double angle brackets, HTML-like comments, triple single quotes,
triple double quotes, or Spanish question marks).
This function serves as a wrapper to `substring_from_delimiters`, allowing
the user to specify a common name for the encloser type. It maps the
given encloser type to its corresponding opening and closing characters.
Args:
input_string (str): The string from which to extract the substring.
encloser_type (str): The type of encloser to look for. Supported types
are "parentheses", "square_brackets", "curly_braces",
"question_marks" (for Spanish ¿?), "angle_brackets",
"double_angle_brackets", "html_comments",
"triple_single_quotes", and "triple_double_quotes".
Returns:
str: The extracted substring. Returns an empty string if the encloser
type is not recognized or if no content is found.
Raises:
TypeError: If 'input_string' or 'encloser_type' is not a string.
ValueError: If the encloser type is not supported, or if there are
mismatched or misplaced delimiters.
Example of use:
>>> extract_content_by_encloser_type("Hello (world)!", "parentheses")
'world'
>>> extract_content_by_encloser_type("Items [apple, banana, orange].", "square_brackets")
'apple, banana, orange'
>>> extract_content_by_encloser_type("Config {host: localhost, port: 8080}.", "curly_braces")
'host: localhost, port: 8080'
>>> extract_content_by_encloser_type("¿Qué tal estás?", "question_marks")
'Qué tal estás'
>>> extract_content_by_encloser_type("This is <important> content.", "angle_brackets")
'important'
>>> extract_content_by_encloser_type("Look <<very important>> data.", "double_angle_brackets")
'very important'
>>> extract_content_by_encloser_type("HTML: ", "html_comments")
' This is a comment '
>>> extract_content_by_encloser_type("Docstring: '''This is a multiline
example with single quotes.'''", "triple_single_quotes") 'This is a multiline example with single quotes.' >>> extract_content_by_encloser_type("Python code: """This is another multiline string."""", "triple_double_quotes") 'This is another multiline string.' >>> extract_content_by_encloser_type("No brackets here.", "square_brackets") '' >>> extract_content_by_encloser_type("Invalid {bracket placement)", "curly_braces") # Raises ValueError
Cost: O(n), where n is the length of the input string. This is due to the underlying
`substring_from_delimiters` function's complexity.
Source code in shortfx/fxString/string_operations.py
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 | |
extract_domain_from_url(url: str) -> str
¶
Extracts the domain (hostname) from a URL string.
Description
Handles URLs with or without a scheme. Returns the netloc
component stripped of any www. prefix, port, auth,
and path segments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL to extract from. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The domain name (e.g. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If url is not a string. |
ValueError
|
If no domain can be extracted. |
Usage Example
extract_domain_from_url("https://www.example.com/path?q=1") 'example.com'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
extract_emails(text: str) -> list[str]
¶
Extracts all email addresses from a text string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to scan. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of extracted email address strings. |
Example
extract_emails("Contact us at info@example.com or sales@test.org") ['info@example.com', 'sales@test.org'] extract_emails("No emails here") []
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
extract_first_number(input_string: str | None) -> int | float | None
¶
Extracts the first integer or float (positive or negative) from a string.
This function searches for the first occurrence of a number within the given string. It handles both integer and decimal numbers, as well as positive and negative signs. If a decimal is found, the number is returned as a float; otherwise, it's returned as an integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str | None
|
The string from which to extract the number. |
required |
Returns:
| Type | Description |
|---|---|
int | float | None
|
The extracted number as an |
int | float | None
|
number is found or the input is invalid. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a matched string cannot be converted to a number. (Though current implementation handles this with a return None) |
Example of use
extract_first_number("The answer is 42.") 42 extract_first_number("Price: -19.99 USD") -19.99 extract_first_number("No numbers here!") None
Source code in shortfx/fxString/string_operations.py
extract_hashtags(text: str) -> list[str]
¶
Extracts #hashtag tokens from a text string.
A hashtag starts with # followed by one or more word characters
(letters, digits, underscore).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of hashtags including the leading |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
extract_hashtags("Hello #world #python3") ['#world', '#python3']
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
extract_last_number(input_string: str | None) -> int | float | None
¶
Extracts the last integer or float (positive or negative) from a string.
This function searches for the last occurrence of a number within the given string. It handles both integer and decimal numbers, as well as positive and negative signs. If a decimal is found, the number is returned as a float; otherwise, it's returned as an integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str | None
|
The string from which to extract the number. |
required |
Returns:
| Type | Description |
|---|---|
int | float | None
|
The extracted number as an |
int | float | None
|
number is found or the input is invalid. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a matched string cannot be converted to a number. (Though current implementation handles this with a return None) |
Example of use
extract_last_number("Item A: 10, Item B: 20.5, Total: 30") 30 extract_last_number("Values: -5.0, +100") 100 extract_last_number("No numbers here!") None
Source code in shortfx/fxString/string_operations.py
extract_mentions(text: str) -> list[str]
¶
Extracts @mention tokens from a text string.
A mention starts with @ followed by one or more word characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of mentions including the leading |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
extract_mentions("Hi @alice and @bob!") ['@alice', '@bob']
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
extract_numbers(input_string: str | None) -> list[int | float]
¶
Extracts all integers and floats (positive or negative) from a string.
This function searches for all occurrences of numbers within the given string. It handles both integer and decimal numbers, as well as positive and negative signs. Returns a list of all numbers found, where each number is returned as an int or float depending on whether it contains a decimal point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str | None
|
The string from which to extract the numbers. |
required |
Returns:
| Type | Description |
|---|---|
list[int | float]
|
A list of extracted numbers as |
list[int | float]
|
Returns an empty list if no numbers are found or the input is invalid. |
Example of use
extract_numbers("The prices are 42 and 19.99") [42, 19.99] extract_numbers("Values: -5, 10.5, +100") [-5, 10.5, 100] extract_numbers("No numbers here!") [] extract_numbers("Mixed: 1.5, 2, -3.14, 42") [1.5, 2, -3.14, 42] extract_numbers(None) []
Cost
O(n) where n is the length of the input string. This is due to the regular expression search operation.
Source code in shortfx/fxString/string_operations.py
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 | |
extract_urls(text: str) -> list[str]
¶
Extracts all URLs from a text string.
Finds http, https, and ftp URLs using a standard pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to scan. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of extracted URL strings. |
Example
extract_urls("Visit https://example.com or http://test.org/path") ['https://example.com', 'http://test.org/path'] extract_urls("No links here") []
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
generate_initials(name: str, separator: str = '.') -> str
¶
Generates initials from a person's name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The full name (e.g. "John Ronald Tolkien"). |
required |
separator
|
str
|
Character placed after each initial. |
'.'
|
Returns:
| Type | Description |
|---|---|
str
|
The initials string (e.g. "J.R.T."). |
Example
generate_initials("John Ronald Tolkien") 'J.R.T.' generate_initials("Albert Einstein", separator="") 'AE'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
generate_password(length: int = 16, *, uppercase: bool = True, lowercase: bool = True, digits: bool = True, special: bool = True) -> str
¶
Generate a cryptographically secure random password.
Description
Uses secrets.choice for randomness. At least one character
from each enabled category is guaranteed, then the remaining
positions are filled from the combined pool and shuffled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
int
|
Total password length (>= number of enabled categories). |
16
|
uppercase
|
bool
|
Include A-Z. Default True. |
True
|
lowercase
|
bool
|
Include a-z. Default True. |
True
|
digits
|
bool
|
Include 0-9. Default True. |
True
|
special
|
bool
|
Include |
True
|
Returns:
| Type | Description |
|---|---|
str
|
A random password string of the requested length. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If length is not an integer. |
ValueError
|
If length is too short or no category is enabled. |
Usage Example
pwd = generate_password(20) len(pwd) 20
Complexity: O(n) where n = length.
Source code in shortfx/fxString/string_operations.py
5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 | |
get_in_text_by_pattern(text: str, pattern_type: str) -> list
¶
Finds and returns all occurrences of a specified pattern type within the given text.
This function acts as a versatile wrapper for common regular expression searches. It takes a text string and a predefined pattern type, then applies the corresponding regex to extract all matching substrings. This centralizes pattern definitions, making your code cleaner and more maintainable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to search within. |
required |
pattern_type
|
str
|
A string indicating the type of pattern to search for. Supported types include: - 'alphanumeric_strings': Strings containing both numbers and letters. - 'letters_and_numbers': Strings with at least one letter and one number. - 'only_letters': Strings containing only letters. - 'uppercase_letters': Strings containing only uppercase letters. - 'lowercase_letters': Strings containing only lowercase letters. - 'words_without_numbers': Words that do not contain any digits. - 'words_length_5': Words exactly 5 characters long. - 'words_length_3_to_5': Words between 3 and 5 characters long. - 'specific_words': Matches 'word1', 'word2', or 'word3'. - 'text_in_parentheses': Text enclosed within parentheses. - 'no_forbidden_word': Lines that do not contain the word "forbidden". - 'all_words': All words in the text. - 'words_starting_with_python': Words that begin with "python". - 'alphanumeric_user_id': User IDs (4-10 alphanumeric characters). - 'strict_email': Strict email address format. - 'broad_email': Broader email address format. - 'integer': Integer numbers. - 'decimal_number': Decimal numbers. - 'only_numbers': Strings containing only numbers. - 'date_yyyy_mm_dd': Dates in YYYY-MM-DD format. - 'time_hh_mm_ss': Time in HH:MM:SS format. - 'time_12_hour': 12-hour time with AM/PM. - 'phone_number_specific': Specific phone number format (e.g., +XX YYYYZZZZZZ). - 'international_phone_number': International phone numbers. - 'visa_credit_card': Visa credit card numbers. - 'txt_filename': Filenames with a .txt extension. - 'ipv4_address': IPv4 addresses. - 'ipv6_address': IPv6 addresses. - 'simple_html_tag': Simple HTML tags. - 'basic_url': Basic URLs starting with http:// or https://. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
A list of all found matches. Returns an empty list if no matches are found or if the pattern_type is not recognized. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unknown pattern_type is provided. |
Example
get_in_text_by_pattern("Hello 123 World! This is a test.", 'alphanumeric_strings') ['Hello 123', 'World']
Cost
The cost of this function is O(N*M) in the worst case, where N is the length
of the input text and M is the length of the regular expression pattern.
This is because the re.findall operation needs to potentially
scan the entire string for all occurrences of the pattern.
Source code in shortfx/fxString/string_operations.py
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 | |
get_line(text: str, line_number: int) -> Optional[str]
¶
Returns a specific line from a multiline string (1-indexed).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input multiline text. |
required |
line_number
|
int
|
The line number to retrieve (1-based). |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The requested line, or None if line_number is out of range. |
Example
get_line("alpha\nbeta\ngamma", 2) 'beta' get_line("single line", 1) 'single line'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
get_substrings(string1: str, string2: str) -> list[dict]
¶
Identifies and returns all common contiguous substrings (matching blocks) between two input strings.
This function utilizes the difflib.SequenceMatcher to find sequences of
identical characters that appear in the same order in both strings.
For each common block found, it provides details such as their positions
in the original strings and their length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string1
|
str
|
The first string for comparison. |
required |
string2
|
str
|
The second string for comparison. |
required |
Returns:
| Type | Description |
|---|---|
list[dict]
|
list[dict]: A list of dictionaries, where each dictionary represents a common contiguous substring (matching block). Each dictionary contains the following keys: - 'string1_start': Starting index of the common substring in string1. - 'string2_start': Starting index of the common substring in string2. - 'length': The length of the common substring. - 'substring': The actual common substring found. Returns an empty list if no common substrings are found. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'string1' or 'string2' are not strings. |
Example
get_substrings("apple tree", "pineapple") [{'string1_start': 0, 'string2_start': 1, 'length': 5, 'substring': 'apple'}]
get_substrings("banana peel", "bandana") [{'string1_start': 0, 'string2_start': 0, 'length': 3, 'substring': 'ban'}, {'string1_start': 5, 'string2_start': 4, 'length': 2, 'substring': 'na'}]
get_substrings("hello world", "python") []
get_substrings("abc", "abc") [{'string1_start': 0, 'string2_start': 0, 'length': 3, 'substring': 'abc'}]
Source code in shortfx/fxString/string_operations.py
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 | |
indent_text(text: str, prefix: str = ' ') -> str
¶
Add a prefix string to the beginning of every line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Input text (may contain multiple lines). |
required |
prefix
|
str
|
String to prepend to each line. Defaults to two spaces. |
' '
|
Returns:
| Type | Description |
|---|---|
str
|
Indented text. |
Example
indent_text("line1\nline2", ">> ") '>> line1\n>> line2'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
interleave_strings(s1: str, s2: str) -> str
¶
Interleave characters from two strings.
Characters are taken alternately from s1 and s2. When one string is exhausted the remainder of the other is appended.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s1
|
str
|
First string. |
required |
s2
|
str
|
Second string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Interleaved result. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either argument is not a string. |
Example
interleave_strings("abc", "12") 'a1b2c'
Complexity: O(n + m)
Source code in shortfx/fxString/string_operations.py
join_to_string(iterable: Iterable[str], separator: str = ' ') -> str
¶
Joins an iterable of strings into a single string with a specified separator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterable
|
Iterable[str]
|
The iterable of strings to join. |
required |
separator
|
str
|
The separator to use between strings. Defaults to a single space. |
' '
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The joined string. |
Example of use
join_to_string(['Hello', 'world!']) 'Hello world!' join_to_string(['apple', 'banana', 'cherry'], separator=', ') 'apple, banana, cherry' join_to_string(('a', 'b', 'c')) 'a b c'
Source code in shortfx/fxString/string_operations.py
kebab_case(text: str) -> str
¶
Convert whitespace-separated text to kebab-case (lowercase, hyphens).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
kebab-cased string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
kebab_case('Hello World') 'hello-world'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
left_bytes(text: str, num_bytes: int) -> str
¶
Return leading characters from text measured in UTF-16 LE bytes.
Equivalent to VBA LeftB. One ASCII character = 2 bytes in UTF-16 LE;
multi-byte characters may occupy more.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
num_bytes
|
int
|
Number of UTF-16 LE bytes to keep. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Substring decoded from the first num_bytes bytes. |
Example
left_bytes("Hello", 6) 'Hel'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
left_substring(original_string: str, num_chars: int) -> str
¶
Extrae un número especificado de caracteres del principio de una cadena.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_string
|
str
|
La cadena de la que se extraerán los caracteres. |
required |
num_chars
|
int
|
El número de caracteres a extraer desde el principio. Si 'num_chars' es mayor que la longitud de la cadena, se devolverá la cadena completa. Si es negativo, se tratará como 0. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La subcadena extraída del principio. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'original_string' no es una cadena o 'num_chars' no es un entero. |
Ejemplos de uso
left_substring("Python", 3) 'Pyt' left_substring("Programacion", 6) 'Progra' left_substring("Hola", 10) # num_chars > longitud 'Hola' left_substring("Ejemplo", 0) '' left_substring("Test", -5) # num_chars negativo ''
Source code in shortfx/fxString/string_operations.py
longest_common_prefix(s1: str, s2: str) -> str
¶
Return the longest common prefix of two strings.
Description
Compares character-by-character from the start until a mismatch is found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s1
|
str
|
First string. |
required |
s2
|
str
|
Second string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The longest common prefix (may be empty string). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either argument is not a string. |
Usage Example
longest_common_prefix("interstellar", "internet") 'inter' longest_common_prefix("abc", "xyz") ''
Complexity: O(min(n, m))
Source code in shortfx/fxString/string_operations.py
longest_common_suffix(s1: str, s2: str) -> str
¶
Return the longest common suffix of two strings.
Description
Compares character-by-character from the end until a mismatch is found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s1
|
str
|
First string. |
required |
s2
|
str
|
Second string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The longest common suffix (may be empty string). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either argument is not a string. |
Usage Example
longest_common_suffix("testing", "running") 'ning' longest_common_suffix("abc", "xyz") ''
Complexity: O(min(n, m))
Source code in shortfx/fxString/string_operations.py
longest_word(text: str) -> str
¶
Returns the longest word in a text string.
Words are split on whitespace. If the text is empty an empty string is returned. Ties are broken by first occurrence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The longest word found, or |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
longest_word("the quick brown fox") 'quick'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
metaphone(text: str) -> str
¶
Computes the Metaphone phonetic code for a word.
Description
Implements Lawrence Philips' original Metaphone algorithm (1990). More accurate than Soundex for English words.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A single word to encode. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The Metaphone code string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If text contains no alphabetic characters. |
Usage Example
metaphone("Thompson") 'TMPSN' metaphone("Smith") 'SM0'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 | |
mid_bytes(text: str, start: int, length: int | None = None) -> str
¶
Return a substring of text measured in UTF-16 LE bytes.
Equivalent to VBA MidB. start is 1-based (first byte is 1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
start
|
int
|
1-based starting byte position. |
required |
length
|
int | None
|
Number of bytes to extract. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Substring decoded from the byte slice. |
Example
mid_bytes("Hello", 3, 4) 'el'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
move_word(input_string: str, from_index: int, to_index: int) -> str
¶
Moves a word from one position to another within a string.
This function splits the input string into words, removes the word at the specified 'from_index', and inserts it at the 'to_index'. The resulting words are then joined back into a single string with spaces. If 'from_index' equals 'to_index', the original string is returned unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string containing the words to manipulate. |
required |
from_index
|
int
|
The 0-based index of the word to move. Must be non-negative and within the range of available words. |
required |
to_index
|
int
|
The 0-based index where to insert the moved word. If 'to_index' is greater than the number of words after removal, the word is appended at the end. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The modified string with the word moved to the new position. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'input_string' is not a string, or if 'from_index' or 'to_index' are not integers. |
ValueError
|
If 'from_index' is negative, or if 'from_index' is out of range for the available words. |
Example Usage
move_word("hello world this is a test", 0, 4) 'world this is a hello test' move_word("apple banana cherry", 1, 0) 'banana apple cherry' move_word("one two three", 2, 2) 'one two three'
Cost
O(n), where n is the length of the input string. This is due to string splitting and joining operations, which are linear in the string length.
Source code in shortfx/fxString/string_operations.py
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 | |
normalize_unicode(text: str, form: str = 'NFC') -> str
¶
Normalize a Unicode string to a canonical form.
Description
Uses Python's unicodedata.normalize with the specified
normalization form: NFC, NFD, NFKC, or NFKD.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to normalize. |
required |
form
|
str
|
Normalization form ( |
'NFC'
|
Returns:
| Type | Description |
|---|---|
str
|
The normalized string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If form is not a valid normalization form. |
Usage Example
normalize_unicode("café", "NFC") == normalize_unicode("café", "NFC") True
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
nysiis(text: str) -> str
¶
Compute the NYSIIS (New York State Identification and Intelligence System) phonetic code.
Description
Produces a phonetic encoding that is generally more accurate than Soundex for English names. Applies prefix/suffix transformations, then walks through the string applying context-sensitive rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to encode. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The NYSIIS code (uppercase, up to 6 characters). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If text is empty after cleaning. |
Usage Example
nysiis("Watkins") 'WATCAN' nysiis("Johnson") 'JANSAN'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 | |
pad_center(text: str, width: int, fillchar: str = ' ') -> str
¶
Centre text within width characters, padding both sides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
width
|
int
|
Desired minimum width. |
required |
fillchar
|
str
|
Single character to pad with (default space). |
' '
|
Returns:
| Type | Description |
|---|---|
str
|
Centre-padded string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string or width is not int. |
ValueError
|
If fillchar is not a single character. |
Usage Example
pad_center('hi', 6, '-') '--hi--'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
pad_end(text: str, width: int, fillchar: str = ' ') -> str
¶
Pad text on the right to reach width characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
width
|
int
|
Desired minimum width. |
required |
fillchar
|
str
|
Single character to pad with (default space). |
' '
|
Returns:
| Type | Description |
|---|---|
str
|
Right-padded string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string or width is not int. |
ValueError
|
If fillchar is not a single character. |
Usage Example
pad_end('hi', 5, '.') 'hi...'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
pad_start(text: str, width: int, fillchar: str = ' ') -> str
¶
Pad text on the left to reach width characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
width
|
int
|
Desired minimum width. |
required |
fillchar
|
str
|
Single character to pad with (default space). |
' '
|
Returns:
| Type | Description |
|---|---|
str
|
Left-padded string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string or width is not int. |
ValueError
|
If fillchar is not a single character. |
Usage Example
pad_start('42', 5, '0') '00042'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
position_in_string(main_string: str, substring: str, start_position: int = 1) -> list[int]
¶
Devuelve una lista de todas las posiciones (basadas en 1) donde se encuentra una subcadena dentro de otra cadena, comenzando la búsqueda desde una posición especificada.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
main_string
|
str
|
La cadena principal donde se realizará la búsqueda. |
required |
substring
|
str
|
La subcadena que se desea encontrar. |
required |
start_position
|
(int, opcional)
|
La posición (basada en 1) donde se inicia la búsqueda. Debe ser un entero positivo. Por defecto es 1. Si la posición de inicio es mayor que la longitud de la cadena, se devuelve una lista vacía. |
1
|
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: Una lista de enteros que representa las posiciones (basadas en 1) donde se encontró la subcadena. La lista estará vacía si no se encuentra la subcadena o si 'start_position' es inválida. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'main_string' o 'substring' no son cadenas, o si 'start_position' no es un entero. |
Ejemplos de uso
position_in_string("banana", "a") [2, 4, 6] position_in_string("ababa", "aba") [1, 3] position_in_string("Mississippi", "ss") [3, 6] position_in_string("Hello World World", "World") [7, 13] position_in_string("Hello World World", "World", 8) # Busca desde la posición 8 [13] position_in_string("Programming is fun, programming is great", "is") [13, 36] position_in_string("banana", "ana", 3) # Busca desde la posición 3 [4] position_in_string("programming", "z") # Subcadena no encontrada [] position_in_string("test", "test", 5) # start_position fuera de rango [] position_in_string("abc", "abcdef") # Subcadena más larga [] position_in_string("hola", "h", 0) # start_position inválida, se maneja como fuera de rango efectivo []
Source code in shortfx/fxString/string_operations.py
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 292 293 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 | |
position_in_string_reverse(main_string: str, substring: str, start_position: int = -1) -> list[int]
¶
Devuelve una lista de todas las posiciones (basadas en 1) donde se encuentra una subcadena dentro de otra cadena, buscando de derecha a izquierda desde una posición especificada. Las posiciones en la lista se devuelven en orden descendente.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
main_string
|
str
|
La cadena principal donde se realizará la búsqueda. |
required |
substring
|
str
|
La subcadena que se desea encontrar. |
required |
start_position
|
(int, opcional)
|
La posición (basada en 1) desde la que se inicia la búsqueda hacia atrás. Un valor de -1 (predeterminado) o un valor mayor que la longitud de la cadena, significa que la búsqueda comienza desde el final de la cadena. Debe ser un entero positivo o -1. |
-1
|
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: Una lista de enteros que representa las posiciones (basadas en 1) donde se encontró la subcadena. La lista estará vacía si no se encuentra la subcadena o si 'start_position' es inválida. Las posiciones se ordenan de forma descendente (de derecha a izquierda). |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'main_string' o 'substring' no son cadenas, o si 'start_position' no es un entero. |
Ejemplos de uso
position_in_string_reverse("banana", "a") [6, 4, 2] position_in_string_reverse("ababa", "aba") [3, 1] position_in_string_reverse("Mississippi", "ss") [6, 3] position_in_string_reverse("Hello World World", "World") [13, 7] position_in_string_reverse("Hello World World", "World", 10) # Busca hacia atrás desde la posición 10 [7] position_in_string_reverse("Programming is fun, programming is great", "is") [36, 13] position_in_string_reverse("banana", "ana", 3) # Busca hacia atrás desde la posición 3 [2] position_in_string_reverse("programming", "z") # Subcadena no encontrada [] position_in_string_reverse("test", "test", 0) # start_position inválida [] position_in_string_reverse("abc", "abcdef") # Subcadena más larga []
Source code in shortfx/fxString/string_operations.py
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 375 376 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 | |
random_string(length: int = 10, secure: bool = True) -> str
¶
Generates a random string of a specified length.
This function creates a random string using a combination of ASCII letters, digits, and punctuation characters. It can use either a cryptographically secure random number generator or a less secure, faster one, depending on the 'secure' flag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
int
|
The desired length of the generated string. Defaults to 10 characters. |
10
|
secure
|
bool
|
If True, uses 'random.SystemRandom()' for cryptographic security. If False, uses 'random.choices()' for faster but less secure generation. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A randomly generated string. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If 'length' is less than 0. |
Example of use
random_string(length=16, secure=True) 'aBc1@EfG2#IjK3$LmN4' # Example output, actual output will vary
Source code in shortfx/fxString/string_operations.py
regex_replace(text: str, pattern: str, replacement: str, case_insensitive: bool = False) -> str
¶
Replaces all occurrences matching a regular expression pattern with a replacement string.
Equivalent to Excel's REGEXREPLACE function. Supports backreferences
in the replacement string (e.g., \1, \g<name>).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to modify. |
required |
pattern
|
str
|
The regular expression pattern to match. |
required |
replacement
|
str
|
The replacement string. Supports regex backreferences. |
required |
case_insensitive
|
bool
|
If True, the pattern matching ignores case. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The text with all matching occurrences replaced. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text, pattern, or replacement is not a string. |
error
|
If the pattern is not a valid regular expression. |
Usage Example
regex_replace("Hello 123 World 456", r"\d+", "X") 'Hello X World X' regex_replace("test@email.com", r"@.*", "@example.com") 'test@example.com' regex_replace("FooBar FooBaz", r"foo", "QUX", case_insensitive=True) 'QUXBar QUXBaz'
Cost: O(n*m), where n is text length and m is pattern complexity.
Source code in shortfx/fxString/string_operations.py
remove_blank_lines(text: str) -> str
¶
Removes all blank (empty or whitespace-only) lines from a text string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input multiline text. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The text with blank lines removed. |
Example
remove_blank_lines("a\n\nb\n \nc") 'a\nb\nc'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
remove_prefix(text: str, prefix: str) -> str
¶
Remove prefix from the start of text if present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
prefix
|
str
|
Prefix to remove. |
required |
Returns:
| Type | Description |
|---|---|
str
|
String without the leading prefix. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If arguments are not strings. |
Usage Example
remove_prefix('unhappy', 'un') 'happy'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
remove_suffix(text: str, suffix: str) -> str
¶
Remove suffix from the end of text if present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
suffix
|
str
|
Suffix to remove. |
required |
Returns:
| Type | Description |
|---|---|
str
|
String without the trailing suffix. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If arguments are not strings. |
Usage Example
remove_suffix('filename.txt', '.txt') 'filename'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
repeat_each_char(text: str, n: int) -> str
¶
Repeat each character in text n times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
n
|
int
|
Repetition count (≥ 0). |
required |
Returns:
| Type | Description |
|---|---|
str
|
String with each character repeated. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If types are incorrect. |
ValueError
|
If n < 0. |
Usage Example
repeat_each_char('abc', 2) 'aabbcc'
Complexity: O(n·m)
Source code in shortfx/fxString/string_operations.py
repeat_string(text: str, times: int) -> str
¶
Repeats a string a given number of times.
Equivalent to Excel REPT function for fxString.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The string to repeat. |
required |
times
|
int
|
Number of times to repeat (must be non-negative). |
required |
Returns:
| Type | Description |
|---|---|
str
|
The repeated string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If times is not an integer. |
ValueError
|
If times is negative. |
Example
repeat_string("ab", 3) 'ababab' repeat_string("", 5) '****'
Complexity: O(n * times)
Source code in shortfx/fxString/string_operations.py
replace_by_position(original_string: str, start_position: int, num_chars: int, new_text: str) -> str
¶
Replaces a segment of a string defined by position and length with new text.
Equivalent to Excel's REPLACE function. Uses 1-based indexing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_string
|
str
|
The original string in which the replacement will be made. |
required |
start_position
|
int
|
The 1-based position of the first character to replace. |
required |
num_chars
|
int
|
The number of characters to replace from start_position. |
required |
new_text
|
str
|
The text to insert in place of the removed segment. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The resulting string after the positional replacement. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If original_string or new_text is not str, or if start_position/num_chars is not int. |
ValueError
|
If start_position < 1 or num_chars < 0. |
Usage Example
replace_by_position("abcdefghijk", 6, 5, "") 'abcdek' replace_by_position("2024", 3, 2, "25") '2025' replace_by_position("Hello World", 1, 5, "Goodbye") 'Goodbye World'
Cost: O(n), where n is the length of original_string.
Source code in shortfx/fxString/string_operations.py
replace_first_occurrence(text: Optional[str], old_substring: str, new_substring: str) -> Optional[str]
¶
Replaces only the first occurrence of a specified substring within a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
old_substring
|
str
|
The substring to search for and replace. |
required |
new_substring
|
str
|
The substring to replace 'old_substring' with. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with the first occurrence replaced, or None if the input 'text' was None. Returns the original string if 'old_substring' is not found. |
Example
replace_first_occurrence("apple banana apple", "apple", "orange") # Returns "orange banana apple" replace_first_occurrence("one two three", "two", "2") # Returns "one 2 three" replace_first_occurrence("no_match", "xyz", "abc") # Returns "no_match" replace_first_occurrence(None, "a", "b") # Returns None
Source code in shortfx/fxString/string_operations.py
replace_last_occurrence(text: Optional[str], old_substring: str, new_substring: str) -> Optional[str]
¶
Replaces only the last occurrence of a specified substring within a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
old_substring
|
str
|
The substring to search for and replace. |
required |
new_substring
|
str
|
The substring to replace 'old_substring' with. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with the last occurrence replaced, or None if the input 'text' was None. Returns the original string if 'old_substring' is not found. |
Example
replace_last_occurrence("apple banana apple", "apple", "orange") # Returns "apple banana orange" replace_last_occurrence("one two three", "two", "2") # Returns "one 2 three" replace_last_occurrence("no_match", "xyz", "abc") # Returns "no_match" replace_last_occurrence(None, "a", "b") # Returns None
Source code in shortfx/fxString/string_operations.py
replace_string(original_string: str, old_substring: str, new_substring: str) -> str
¶
Reemplaza todas las ocurrencias de una subcadena en una cadena con otra subcadena.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_string
|
str
|
La cadena original en la que se realizará el reemplazo. |
required |
old_substring
|
str
|
La subcadena que se buscará y reemplazará. |
required |
new_substring
|
str
|
La subcadena con la que se reemplazarán las ocurrencias. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La nueva cadena con las subcadenas reemplazadas. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'original_string', 'old_substring' o 'new_substring' no son cadenas. |
Ejemplos de uso
replace_string("Hola mundo", "mundo", "Python") 'Hola Python' replace_string("uno dos uno tres", "uno", "diez") 'diez dos diez tres' replace_string("abcabc", "b", "xyz") 'axyzcAxyzc' replace_string("Sin cambios", "no existe", "nada") 'Sin cambios' replace_string("AAA", "A", "B") 'BBB'
Source code in shortfx/fxString/string_operations.py
reverse_string(input_string: str) -> str
¶
Invierte una cadena de texto.
Esta función toma una cadena de entrada y devuelve una nueva cadena con los caracteres en orden inverso.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
La cadena de texto que se desea invertir. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La cadena invertida. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si la entrada no es una cadena de texto. |
Ejemplos de uso
reverse_string("hola") 'aloh' reverse_string("Python") 'nohtyP' reverse_string("12345") '54321' reverse_string("") '' reverse_string("programación") 'nóicamargorp'
Source code in shortfx/fxString/string_operations.py
reverse_words(text: str) -> str
¶
Reverses the order of words in a string.
Individual words keep their original spelling; only their sequence is inverted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Text with word order reversed. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
reverse_words("hello world foo") 'foo world hello'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
right_bytes(text: str, num_bytes: int) -> str
¶
Return trailing characters from text measured in UTF-16 LE bytes.
Equivalent to VBA RightB.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
num_bytes
|
int
|
Number of UTF-16 LE bytes to keep from the end. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Substring decoded from the last num_bytes bytes. |
Example
right_bytes("Hello", 6) 'llo'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
right_substring(original_string: str, num_chars: int) -> str
¶
Extrae un número especificado de caracteres del final de una cadena.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_string
|
str
|
La cadena de la que se extraerán los caracteres. |
required |
num_chars
|
int
|
El número de caracteres a extraer desde el final. Si 'num_chars' es mayor que la longitud de la cadena, se devolverá la cadena completa. Si es negativo, se tratará como 0. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La subcadena extraída del final. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'original_string' no es una cadena o 'num_chars' no es un entero. |
Ejemplos de uso
right_substring("Python", 3) 'hon' right_substring("Programacion", 6) 'macion' right_substring("Hola", 10) # num_chars > longitud 'Hola' right_substring("Ejemplo", 0) '' right_substring("Test", -5) # num_chars negativo ''
Source code in shortfx/fxString/string_operations.py
rot13(text: str) -> str
¶
Apply ROT13 rotation to text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
ROT13-rotated string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
rot13('hello') 'uryyb'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
rotate_words(text: Optional[str], num_rotations: int, rotate_direction: str) -> Optional[str]
¶
Cyclically rotates words within a text string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string containing words to rotate. Can be None. |
required |
num_rotations
|
int
|
The number of positions to rotate the words. Must be a non-negative integer. |
required |
rotate_direction
|
str
|
The direction of the rotation. Must be 'left' (first word moves to end) or 'right' (last word moves to beginning). |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The string with words rotated, or None if the input 'text' was None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If 'num_rotations' is negative, or 'rotate_direction' is not 'left' or 'right'. |
Source code in shortfx/fxString/string_operations.py
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 | |
run_length_decode(encoded: str) -> str
¶
Decode a run-length encoded string.
Expects the format produced by :func:run_length_encode
(count-character pairs like "3a2b1c").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoded
|
str
|
RLE-encoded string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Decoded string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If encoded is not a string. |
ValueError
|
If the format is invalid. |
Example
run_length_decode("3a2b1c") 'aaabbc'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
run_length_encode(text: str) -> str
¶
Run-length encode a string.
Consecutive identical characters are replaced by their count followed by the character.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Input string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
RLE-encoded string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
run_length_encode("aaabbc") '3a2b1c'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
search_text(find_text: str, within_text: str, start_num: int = 1) -> int
¶
Case-insensitive text search returning 1-based position.
Description
Finds the position of find_text within within_text, ignoring case. Equivalent to Excel SEARCH.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
find_text
|
str
|
Text to find. |
required |
within_text
|
str
|
Text to search in. |
required |
start_num
|
int
|
Starting position, 1-based (default 1). |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
1-based position of the first match. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If inputs are not valid. |
ValueError
|
If find_text is not found or start_num < 1. |
Example
search_text('margin', 'Profit Margin') 8 search_text('M', 'miriam mcgovern') 1
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
shortest_word(text: str) -> str
¶
Returns the shortest word in a text string.
Words are split on whitespace. If the text is empty an empty string is returned. Ties are broken by first occurrence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The shortest word found, or |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Example
shortest_word("the quick brown fox") 'the'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
slugify(text: str, separator: str = '-') -> str
¶
Converts text to a URL-friendly slug.
Removes accents, lowercases, replaces non-alphanumeric characters with a separator, and collapses consecutive separators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
separator
|
str
|
Character used between words (default |
'-'
|
Returns:
| Type | Description |
|---|---|
str
|
A URL-safe slug string. |
Example
slugify("Hola Mundo!") 'hola-mundo' slugify(" Café con Leche ") 'cafe-con-leche' slugify("Python 3.12 is great", separator="_") 'python_3_12_is_great'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
snake_to_camel(text: str) -> str
¶
Convert snake_case to camelCase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Snake-cased string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
camelCase string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
snake_to_camel('hello_world') 'helloWorld'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
sort_lines(text: str, reverse: bool = False) -> str
¶
Sorts lines in a text string alphabetically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input multiline text. |
required |
reverse
|
bool
|
If True, sorts in descending order. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
The text with lines sorted. |
Example
sort_lines("banana\napple\ncherry") 'apple\nbanana\ncherry' sort_lines("b\na\nc", reverse=True) 'c\nb\na'
Complexity: O(n log n)
Source code in shortfx/fxString/string_operations.py
soundex(text: str) -> str
¶
Computes the Soundex phonetic code for a word.
Description
Implements the American Soundex algorithm (Robert C. Russell, 1918). Useful for matching names that sound alike but are spelled differently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A single word to encode. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A 4-character Soundex code (letter + 3 digits). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If text contains no alphabetic characters. |
Usage Example
soundex("Robert") 'R163' soundex("Rupert") 'R163'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 | |
split_all(text_to_tokenize: str, delimiter_pattern: str = None, return_joined: bool = False) -> list[str] | tuple[list[str], str]
¶
Splits the input string into a list of words (tokens) based on a comprehensive set of delimiters.
This function is designed to break down a continuous string of text into individual meaningful units (tokens). By default, it uses a pattern that includes common punctuation, symbols, and various whitespace characters as delimiters. You can also provide a custom regex pattern to define specific splitting behavior. Empty strings resulting from the split operation are automatically removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_to_tokenize
|
str
|
The input string to be tokenized. |
required |
delimiter_pattern
|
str
|
A custom regular expression pattern to use as a delimiter. If None, a default comprehensive pattern including punctuation, symbols, and whitespace will be used. Defaults to None. |
None
|
return_joined
|
bool
|
If True, returns a tuple containing the split list and the joined string using join_to_string with default separator. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[str] | tuple[list[str], str]
|
list[str] | tuple[list[str], str]: A list of strings, where each string is a token (word). Returns an empty list if the input is None or an empty string after processing. If return_joined is True, returns a tuple (split_list, joined_string). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'text_to_tokenize' is not a string or None, or if 'delimiter_pattern' is provided but not a string. |
Example of use
split_all("Hello, world! This is a test.") ['Hello', 'world', 'This', 'is', 'a', 'test'] split_all(" Another example with extra spaces! ") ['Another', 'example', 'with', 'extra', 'spaces'] split_all("item1/item2-item3", delimiter_pattern=r'[/-]+') ['item1', 'item2', 'item3'] split_all("Python's cool!") ['Python', 's', 'cool'] split_all(None) [] split_all("Hello world", return_joined=True) (['Hello', 'world'], 'Hello world')
Cost
O(N), where N is the length of the input string. This is due to the regular expression splitting, which is generally linear with respect to the input size.
Source code in shortfx/fxString/string_operations.py
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 | |
split_between_delimiters(text: Optional[str], delimiter_key: str) -> Optional[List[str]]
¶
Splits the input string into a list of substrings, using the content within the specified delimiters as separators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string to be split. Can be None. |
required |
delimiter_key
|
str
|
A key representing the type of delimiters to use. Supported: '/ /', '()', '[]', '{}', '<>', '""', "''", '$$' |
required |
Returns:
| Type | Description |
|---|---|
Optional[List[str]]
|
Optional[List[str]]: A list of substrings if the input was not None, otherwise None. The delimiters and their contents are not included in the resulting substrings. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported delimiter key is provided. |
Example of use
split_between_delimiters("hello(world)foo[bar]baz", "()") ['hello', 'foo[bar]baz'] split_between_delimiters("before /comment/ after", "/ /") ['before ', ' after']
Source code in shortfx/fxString/string_operations.py
split_by_substrings(p_iparse: str, p_separators: list[str]) -> list[str]
¶
Splits a string by a list of keyword separators, keeping the separator with its content.
Description
This function takes a string (like a SQL script) and splits it into a list of substrings. Each substring in the output list begins with one of the specified separators. It is designed to handle complex inputs where separators mark the beginning of a new logical block. This implementation correctly handles Oracle SQL scripts containing both standard SQL statements and PL/SQL blocks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_iparse
|
str
|
The input string to be split. |
required |
p_separators
|
list[str]
|
A list of strings to use as separators. These should be the keywords that start each block. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: A list of strings, where each element is a complete, executable command block from the input script. |
Example of use
sql_script = "CREATE TABLE T1 (c1 INT); COMMENT ON TABLE T1 IS 'test'; BEGIN NULL; END; /" separators = ["CREATE TABLE", "COMMENT ON", "BEGIN"] split_by_substrings(sql_script, separators) ["CREATE TABLE T1 (c1 INT);", "COMMENT ON TABLE T1 IS 'test';", "BEGIN NULL; END; /"]
Source code in shortfx/fxString/string_operations.py
squeeze(text: str, char: str) -> str
¶
Reduce consecutive runs of char to a single occurrence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
char
|
str
|
Single character to squeeze. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Squeezed string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If types are incorrect. |
ValueError
|
If char is not a single character. |
Usage Example
squeeze('aaabbbccc', 'b') 'aaabccc'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
string_merge(string1: str, string2: str, base: Optional[str] = None) -> str
¶
Merges two strings based on a common base string (3-way merge).
Description
Performs a 3-way merge of two strings (string1 and string2) relative to a
common ancestor (base). It automatically resolves non-conflicting changes
(additions, deletions, modifications). When conflicting changes are detected
(overlapping edits or different insertions at the same position), it marks
the conflict region using the pattern <<<<<<< ++ SOURCE ======= ++ TARGET >>>>>>>.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string1
|
str
|
The first modified string (source). |
required |
string2
|
str
|
The second modified string (target). |
required |
base
|
Optional[str]
|
The common ancestor string. If None, defaults to an empty string. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The merged string, potentially containing conflict markers. |
Usage Example
base = '123456' s1 = '1234567' # Added 7 s2 = '0123456' # Added 0 string_merge(s1, s2, base) '01234567'
s1 = '12a456' # Modified 3 to a s2 = '12b456' # Modified 3 to b string_merge(s1, s2, base) '12<<<<<<< ++ a ======= ++ b >>>>>>>456'
Cost
O(N*M) due to the complexity of calculating diffs (SequenceMatcher).
Source code in shortfx/fxString/string_operations.py
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 | |
string_xor(a: str, b: str) -> str
¶
XOR two equal-length strings character by character.
Returns a string of XOR'd character ordinals as two-digit hex codes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str
|
First string. |
required |
b
|
str
|
Second string (same length as a). |
required |
Returns:
| Type | Description |
|---|---|
str
|
Hex-encoded XOR result. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If arguments are not strings. |
ValueError
|
If lengths differ. |
Usage Example
string_xor('abc', 'ABC') '202020'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
strip_html_tags(text: str) -> str
¶
Removes all HTML/XML tags from a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string containing HTML tags. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The string with all tags removed. |
Example
strip_html_tags("
Hello World
") 'Hello World' strip_html_tags("No tags here") 'No tags here'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
substitute(text: str, old_text: str, new_text: str, instance_num: int = 0) -> str
¶
Substitutes new text for old text in a string.
Description
Replaces occurrences of old_text with new_text. If instance_num is 0, replaces all occurrences. Otherwise replaces only the Nth occurrence. Equivalent to Excel SUBSTITUTE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The original text. |
required |
old_text
|
str
|
The text to find and replace. |
required |
new_text
|
str
|
The replacement text. |
required |
instance_num
|
int
|
Which occurrence to replace (0 = all, 1 = first, etc.). |
0
|
Returns:
| Type | Description |
|---|---|
str
|
The text with substitutions applied. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text, old_text, or new_text are not strings. |
ValueError
|
If instance_num is negative. |
Example
substitute("one fish two fish", "fish", "cat") 'one cat two cat' substitute("one fish two fish", "fish", "cat", 2) 'one fish two cat'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
substring(original_string: str, start_position: int, length: int) -> str
¶
Extrae una subcadena de una cadena a partir de una posición inicial y con una longitud específica.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_string
|
str
|
La cadena de la que se extraerá la subcadena. |
required |
start_position
|
int
|
La posición inicial desde la que se comenzará la extracción. Las posiciones se basan en 1 (el primer carácter es 1). Si 'start_position' es 0 o negativo, se ajusta a 1. Si 'start_position' es mayor que la longitud de la cadena, se devolverá una cadena vacía. |
required |
length
|
int
|
La longitud de la subcadena a extraer. Si 'length' es negativo, se tratará como 0. Si la longitud excede el final de la cadena, se extraerá hasta el final. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La subcadena extraída. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si 'original_string' no es una cadena, o 'start_position' o 'length' no son enteros. |
Ejemplos de uso
substring("Python Programacion", 1, 6) # "Python" 'Python' substring("Python Programacion", 8, 4) # "Prog" 'Prog' substring("Hola Mundo", 6, 5) # "Mundo" 'Mundo' substring("Ejemplo", 3, 10) # Desde el 3er caracter, hasta el final 'emplo' substring("Corto", 10, 5) # start_position fuera de rango '' substring("Test", 1, 0) # length es 0 '' substring("ABC", 1, -2) # length es negativo '' substring("XYZ", -5, 2) # start_position negativo (se ajusta a 1) 'XY'
Source code in shortfx/fxString/string_operations.py
substring_after_last_digit(input_string: str) -> str
¶
Extracts the substring after the last occurrence of a digit in a given string.
This function iterates through the input string in reverse order. When the last digit is found, it returns the portion of the string that follows this digit. If no digits are found, an empty string is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string from which to extract the substring. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The substring after the last digit, or an empty string if no digits are present. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
Example of use
substring_after_last_digit("abc123def456ghi") 'ghi' substring_after_last_digit("no_digits_here") '' substring_after_last_digit("123start") 'start' substring_after_last_digit("end123") '' substring_after_last_digit("") ''
Source code in shortfx/fxString/string_operations.py
substring_before_first_digit(input_string: str) -> str
¶
Extracts the substring before the first occurrence of a digit in a given string.
This function iterates through the input string character by character. If a digit is encountered, it returns the portion of the string that precedes this digit. If no digits are found, the entire original string is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string from which to extract the substring. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The substring before the first digit, or the original string if no digits are present. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
Example of use
substring_before_first_digit("abc123def") 'abc' substring_before_first_digit("no_digits_here") 'no_digits_here' substring_before_first_digit("123start") '' substring_before_first_digit("") ''
Source code in shortfx/fxString/string_operations.py
substring_between_delimiters(text: Optional[str], delimiter_key: str) -> Optional[List[str]]
¶
Extracts all substrings found between a specified pair of delimiters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string from which to extract substrings. Can be None. |
required |
delimiter_key
|
str
|
A key representing the type of delimiters to use. Supported: '/ /', '()', '[]', '{}', '<>', '""', "''", '$$' |
required |
Returns:
| Type | Description |
|---|---|
Optional[List[str]]
|
Optional[List[str]]: A list of extracted substrings (excluding the delimiters themselves), or None if the input was None. Returns an empty list if no matches are found. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported delimiter key is provided. |
Example of use
substring_between_delimiters("hello(world)foo[bar]baz", "()") ['world'] substring_between_delimiters("code / multiline\ncomment / more code", "/ /") [' multiline\ncomment ']
Source code in shortfx/fxString/string_operations.py
substring_between_pattern(input_string: str, pattern: str) -> str | None
¶
Extracts the substring located between the first two occurrences of a specified pattern within a given string.
This function is particularly useful for parsing structured text where relevant information is consistently delimited by a repeating pattern. The pattern is treated as a literal string (special regex characters are escaped).
Args: input_string (str): The string from which to extract the substring. pattern (str): The string pattern that acts as both the start and end delimiter.
Returns: str | None: The extracted substring, stripped of leading/trailing whitespace. Returns None if the input string is empty, the pattern is empty, or if the pattern is not found twice in the string.
Raises: TypeError: If 'input_string' or 'pattern' are not strings.
Example: >>> substring_between_pattern("Data:VALUE:End", ":") 'VALUE'
>>> substring_between_pattern("START_data_END", "_")
'data'
>>> substring_between_pattern("No matching patterns", "ABC")
None
>>> substring_between_pattern("One pattern onlyABC", "ABC")
None
>>> substring_between_pattern("Multiple///segments///here", "///")
'segments'
>>> substring_between_pattern("Edge case: pattern at start: content: pattern at end", ":")
' pattern at start'
>>> substring_between_pattern(" Pattern
Content
Pattern ", "Pattern")
'
Content
'
Source code in shortfx/fxString/string_operations.py
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 | |
substring_from_delimiters(input_string: str, opening_delimiter: str = '(', closing_delimiter: str = ')') -> str
¶
Extracts the substring enclosed within the first pair of specified delimiters in a given string.
This function finds the content between the first occurrence of the opening_delimiter
and the last occurrence of the closing_delimiter. It is useful for parsing
data where key information is consistently enclosed within a specific pair of characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string from which to extract the substring. |
required |
opening_delimiter
|
str
|
The character(s) marking the beginning of the substring. Defaults to "(". |
'('
|
closing_delimiter
|
str
|
The character(s) marking the end of the substring. Defaults to ")". |
')'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The substring found between the delimiters. Returns an empty string if no matching delimiters are found or if the content is empty. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'input_string', 'opening_delimiter', or 'closing_delimiter' is not a string. |
ValueError
|
If an empty string is provided as a delimiter, if a closing delimiter is found before an opening one, or if the delimiters are not properly balanced (e.g., missing one). |
Example of use
substring_from_delimiters("This is a (test) string.", "(", ")") 'test' substring_from_delimiters("Another [example with multiple] brackets [like this].", "[", "]") 'example with multiple] brackets [like this' substring_from_delimiters("A {curly} brace example.", "{", "}") 'curly' substring_from_delimiters("No delimiters here.", "(", ")") '' substring_from_delimiters("Empty <> content.", "<", ">") '' substring_from_delimiters("{Starts with braces}", "{", "}") 'Starts with braces'
Cost: O(n), where n is the length of the input string. This is because find and rfind
operations traverse the string linearly in the worst case.
Source code in shortfx/fxString/string_operations.py
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 | |
substring_on_left(text: Optional[str], pattern: str) -> Optional[str]
¶
Extracts the substring that appears before the first occurrence of a specified pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
pattern
|
str
|
The pattern to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The substring before the first 'pattern' occurrence. Returns the original string if the pattern is not found. Returns an empty string if the pattern is at the very beginning of the string. Returns None if the input 'text' was None. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'pattern' is not a string. |
Example of use
substring_on_left("hello world", " ") "hello"
substring_on_left("apple,banana,orange", ",") "apple"
substring_on_left("test", "xyz") "test" # Pattern not found, returns original string
substring_on_left("last char.", ".") "last char"
substring_on_left(" first", " ") "" # Pattern at the beginning
substring_on_left(None, "pattern") None
Source code in shortfx/fxString/string_operations.py
substring_on_right(text: Optional[str], pattern: str) -> Optional[str]
¶
Extracts the substring that appears after the first occurrence of a specified pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. Can be None. |
required |
pattern
|
str
|
The pattern to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The substring after the first 'pattern' occurrence. Returns the original string if the pattern is not found. Returns an empty string if the pattern is at the very end of the string. Returns None if the input 'text' was None. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'pattern' is not a string. |
Example of use
substring_on_right("hello world", " ") "world"
substring_on_right("apple,banana,orange", ",") "banana,orange"
substring_on_right("test", "xyz") "test" # Pattern not found, returns original string
substring_on_right("last char.", ".") "" # Pattern at the very end
substring_on_right("first char", "first char") "" # Pattern is the entire string
substring_on_right(None, "pattern") None
Source code in shortfx/fxString/string_operations.py
surround(text: str, wrapper: str) -> str
¶
Wraps a text with a given string on both sides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
wrapper
|
str
|
The string to prepend and append. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The surrounded text. |
Example
surround("hello", "") 'hello**' surround("world", "'") "'world'"
Complexity: O(1)
Source code in shortfx/fxString/string_operations.py
swap_case(text: str) -> str
¶
Swap the case of every character in text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Case-swapped string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
swap_case('Hello World') 'hELLO wORLD'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
text_after(text: str, delimiter: str, instance_num: int = 1) -> str
¶
Returns text that occurs after a given delimiter.
Description
Returns the portion of text after the Nth occurrence of the delimiter. Negative instance_num searches from the end. Equivalent to Excel TEXTAFTER.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text to search. |
required |
delimiter
|
str
|
The delimiter to search for. |
required |
instance_num
|
int
|
Which occurrence (1 = first, -1 = last, etc.). |
1
|
Returns:
| Type | Description |
|---|---|
str
|
The text after the specified occurrence of the delimiter. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text or delimiter are not strings. |
ValueError
|
If instance_num is 0 or delimiter is not found. |
Example
text_after("hello-world-test", "-") 'world-test' text_after("hello-world-test", "-", 2) 'test' text_after("hello-world-test", "-", -1) 'test'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 | |
text_before(text: str, delimiter: str, instance_num: int = 1) -> str
¶
Returns text that occurs before a given delimiter.
Description
Returns the portion of text before the Nth occurrence of the delimiter. Negative instance_num searches from the end. Equivalent to Excel TEXTBEFORE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text to search. |
required |
delimiter
|
str
|
The delimiter to search for. |
required |
instance_num
|
int
|
Which occurrence (1 = first, -1 = last, etc.). |
1
|
Returns:
| Type | Description |
|---|---|
str
|
The text before the specified occurrence of the delimiter. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text or delimiter are not strings. |
ValueError
|
If instance_num is 0 or delimiter is not found. |
Example
text_before("hello-world-test", "-") 'hello' text_before("hello-world-test", "-", 2) 'hello-world' text_before("hello-world-test", "-", -1) 'hello-world'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 | |
text_split(text: str, col_delimiter: str = None, row_delimiter: str = None) -> list
¶
Splits text into rows and/or columns using delimiters.
Description
Splits a string by column and/or row delimiters, returning a 2-D list of strings. Equivalent to Excel TEXTSPLIT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text to split. |
required |
col_delimiter
|
str
|
Delimiter for splitting into columns. If None, no column splitting. |
None
|
row_delimiter
|
str
|
Delimiter for splitting into rows. If None, no row splitting. |
None
|
Returns:
| Type | Description |
|---|---|
list
|
A 2-D list of strings if both delimiters are provided, |
list
|
a 1-D list if only one delimiter is provided. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
ValueError
|
If both delimiters are None. |
Example
text_split("a,b,c", col_delimiter=",") ['a', 'b', 'c'] text_split("a,b;c,d", col_delimiter=",", row_delimiter=";") [['a', 'b'], ['c', 'd']] text_split("row1;row2;row3", row_delimiter=";") ['row1', 'row2', 'row3']
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
title_case(text: str) -> str
¶
Convert text to title case, capitalising the first letter of each word.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Title-cased string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
title_case('hello world') 'Hello World'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
truncate_string(input_string: Optional[str], target_length: int = 255, align: str = 'right') -> Optional[str]
¶
Truncates a string to a specified target length from the left or right.
If the input_string's length exceeds target_length, it is shortened.
The align parameter dictates which part of the string is preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
Optional[str]
|
The string to be truncated. Can be None. |
required |
target_length
|
int
|
The desired maximum length of the string. Must be a non-negative integer. |
255
|
align
|
str
|
The alignment for truncation. 'left' to truncate from the left (keeping the right part of the string). 'right' to truncate from the right (keeping the left part of the string). Defaults to 'right'. |
'right'
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: The truncated string. Returns the original string if its length
is within the limit, or if |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
Example of use
truncate_string("abcdefg", 5) 'abcde' truncate_string("abcdefg", 5, align='left') 'cdefg' truncate_string("short", 10) 'short' truncate_string(None, 5) None truncate_string("long string", 0) '' truncate_string("another long string", 7, align='right') 'another' truncate_string("another long string", 7, align='left') 'string'
Source code in shortfx/fxString/string_operations.py
truncate_with_ellipsis(text: str, max_len: int, ellipsis: str = '...') -> str
¶
Truncate text to max_len characters, appending ellipsis if cut.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
max_len
|
int
|
Maximum length INCLUDING ellipsis. |
required |
ellipsis
|
str
|
Suffix to append (default |
'...'
|
Returns:
| Type | Description |
|---|---|
str
|
Truncated string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If types are invalid. |
ValueError
|
If max_len < len(ellipsis). |
Usage Example
truncate_with_ellipsis('hello world', 8) 'hello...'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
word_at(text: str, index: int) -> str
¶
Return the word at the given 1-indexed position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Input text. |
required |
index
|
int
|
1-based word position. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The word at the specified position. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range. |
Example
word_at("The quick brown fox", 3) 'brown'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
wrap_text(text: str, width: int = 80) -> str
¶
Wraps text to a specified line width at word boundaries.
Splits long lines without breaking words, inserting newlines at the nearest whitespace before the width limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
width
|
int
|
Maximum characters per line (default 80). |
80
|
Returns:
| Type | Description |
|---|---|
str
|
Word-wrapped text with newlines inserted. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If width is less than 1. |
Example
wrap_text("The quick brown fox jumps over the lazy dog", width=20) 'The quick brown fox\njumps over the lazy\ndog'
Complexity: O(n)
Source code in shortfx/fxString/string_operations.py
zigzag_case(text: str) -> str
¶
Alternate character case: even indices lower, odd indices upper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Zigzag-cased string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If text is not a string. |
Usage Example
zigzag_case('hello') 'hElLo'
Complexity: O(n)