string_format¶
shortfx.fxString.string_format
¶
String Formatting and Normalization Functions.
This module provides functions for formatting, normalizing, and standardizing strings according to various conventions and requirements. It includes utilities for formatting names, addresses, identifiers, and other text data.
Key Features: - Data masking and anonymization - Date and number formatting - Name and company name formatting - Email, URL, and domain formatting - String case transformations - Symbol and space normalization - Character set filtering - Legal form parsing - SQL quoting and escaping
Functions¶
apply_string_format(input_string: str, format_code: int) -> str
¶
Applies a specified casing format to a given string.
This function transforms the input string based on a numeric format code, converting it to lowercase, capitalized, title case, or uppercase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to which the format will be applied. |
required |
format_code
|
int
|
The integer code representing the desired format: 1 for lowercase, 2 for capitalized, 3 for title case, 4 for uppercase. Any other value defaults to uppercase. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted string. |
Example
apply_string_format("Hello World", 1) 'hello world' apply_string_format("hello world", 2) 'Hello world' apply_string_format("hello world", 3) 'Hello World' apply_string_format("hello world", 4) 'HELLO WORLD' apply_string_format("test", 99) # Defaults to uppercase 'TEST'
Source code in shortfx/fxString/string_format.py
ascii_string(input_string: str | None) -> str | None
¶
Converts a string to its ASCII representation, ignoring characters that cannot be encoded in ASCII.
This function is useful for cleaning strings by removing non-ASCII characters, which can be beneficial when working with systems or formats that only support ASCII. If the input is None, it returns None directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str | None
|
The string to convert. Can be None. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The ASCII-encoded string. Returns None if the input was None. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'input_string' is provided and is not a string or None. |
Example
ascii_string("Héllø Wörld!") 'Hll Wrld!'
ascii_string("This is an ASCII string.") 'This is an ASCII string.'
ascii_string(None) is None True
ascii_string("Grüße") 'Gre'
Source code in shortfx/fxString/string_format.py
auto_format_string(input_string: str) -> str
¶
Automatically formats a string to either its original case (if all upper/lower) or capitalized.
This function checks if the input string is entirely uppercase or lowercase. If so, it returns the string as is. Otherwise, it capitalizes the first letter of the string. This is useful for standardizing text where a consistent initial capitalization is desired unless the string is already uniformly cased.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to format automatically. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The automatically formatted string. |
Example
auto_format_string("HELLO") 'HELLO' auto_format_string("hello") 'hello' auto_format_string("hello world") 'Hello world' auto_format_string("Hello world") 'Hello world'
Source code in shortfx/fxString/string_format.py
autoformat(data_input: Any, locale: str = 'en_US') -> str
¶
Automatically formats an input value as a date or a number based on its type and content, adhering to the specified locale conventions for both parsing and default output formats. If unable to format, returns the original input as a string.
This function attempts to interpret the input as a datetime object. If it's not a datetime object and appears to be a string, it tries to parse it as a date using locale-specific formats. If date parsing fails, it then attempts to interpret and format the input as a number (int, float, or numeric string), again respecting the locale's number formatting conventions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_input
|
Any
|
The input data to be auto-formatted. Can be a datetime object, an int, a float, or a string that represents a date or a number. |
required |
locale
|
str
|
The locale to use for both date and number formatting. Supported locales are "en_US" (Anglo-Saxon) and "es_ES" (European). Defaults to "en_US". |
'en_US'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The automatically formatted string representation of the input, or the original input converted to string if formatting fails. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input type is fundamentally unsupported. |
Example of use
from datetime import datetime
Successful formatting¶
autoformat("10/26/2023", locale="en_US") '2023-10-26' autoformat("26/10/2023", locale="es_ES") '26/10/2023' autoformat(1234567.89, locale="en_US") '1,234,567.89' autoformat("98.765,43", locale="es_ES") '98.765,43'
Fallback to original data¶
autoformat("not a date or number", locale="en_US") 'not a date or number' autoformat([1, 2, 3], locale="es_ES") # Unsupported type, will return str([1, 2, 3]) '[1, 2, 3]' autoformat(None) 'None'
Source code in shortfx/fxString/string_format.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 | |
camel_to_snake(text: str) -> str
¶
Converts a camelCase or PascalCase string to snake_case.
Handles sequences of uppercase letters (acronyms) correctly:
"getHTTPResponse" becomes "get_http_response".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The camelCase or PascalCase string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The snake_case equivalent. |
Example
camel_to_snake("camelCase") 'camel_case' camel_to_snake("PascalCase") 'pascal_case' camel_to_snake("getHTTPResponse") 'get_http_response' camel_to_snake("already_snake") 'already_snake'
Complexity: O(n)
Source code in shortfx/fxString/string_format.py
capitalize_string(input_string: str, mode: str = 'all') -> str
¶
Capitalizes words in a string, with an optional mode to handle specific particles.
This function capitalizes the first letter of each word in the input string.
It can optionally handle 'particles' (prepositions, articles, conjunctions)
in Spanish by keeping them lowercase when mode is 'location' and they
are not the very first word of a segment. It intelligently splits the string
by spaces, hyphens, and slashes to process each word or segment independently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to be capitalized. |
required |
mode
|
str
|
The capitalization mode. 'all': Capitalize every word. 'location': Capitalize every word, but keep specified particles (e.g., 'de', 'el') lowercase unless they are the first word in a segment. Defaults to 'all'. |
'all'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The string with words capitalized according to the specified mode. |
Example
capitalize_string("via del mar", mode='location') 'Via del Mar' capitalize_string("san-pablo", mode='location') 'San-Pablo' capitalize_string("juan perez") 'Juan Perez' capitalize_string("calle de la amargura", mode='location') 'Calle de la Amargura' capitalize_string("felipe ii/madrid", mode='location') 'Felipe II/Madrid'
Source code in shortfx/fxString/string_format.py
dollar(number: Union[int, float], decimals: int = 2) -> str
¶
Format number as currency text with dollar sign.
Description
Converts a number to text using currency format with a dollar sign, commas, and specified decimals. Equivalent to Excel DOLLAR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number
|
Union[int, float]
|
Numeric value to format. |
required |
decimals
|
int
|
Decimal places (default 2). |
2
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Dollar-formatted text. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If number is not numeric or decimals not int. |
Example
dollar(1234.567) '$1,234.57' dollar(-1234.567, 1) '-$1,234.6'
Complexity: O(1)
Source code in shortfx/fxString/string_format.py
fixed(number: Union[int, float], decimals: int = 2, no_commas: bool = False) -> str
¶
Format number with a fixed number of decimal places.
Description
Rounds a number to the given decimal places and returns a text string, optionally without thousands separators. Equivalent to Excel FIXED.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number
|
Union[int, float]
|
Numeric value to format. |
required |
decimals
|
int
|
Decimal places (default 2). |
2
|
no_commas
|
bool
|
If True, suppress thousands separators. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Formatted text representation. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If number is not numeric or decimals not int. |
Example
fixed(1234567.89, 1) '1,234,567.9' fixed(1234567.89, 1, True) '1234567.9'
Complexity: O(1)
Source code in shortfx/fxString/string_format.py
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 | |
flat_vowels(input_string: str) -> str
¶
Removes only acute accents from vowels while preserving 'ñ', 'ç', and 'ü'.
This function iterates through the input string, applying specific rules for 'ñ', 'ç', and 'ü' to ensure they remain unchanged. For other characters, it normalizes them to decompose accented vowels into their base letter and a diacritic, then filters out only the diacritics. The final string is converted to uppercase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to process. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The string with only acute accents removed, with 'ñ', 'ç', and 'ü' preserved, and converted to uppercase. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
Example
flat_vowels("España, cómo estás, pingüino, Cançao, Corazón") 'ESPAÑA, COMO ESTAS, PINGÜINO, CANÇAO, CORAZON'
Cost
The cost of this function is O(n), where 'n' is the length of the input string. This is because it processes each character individually.
Source code in shortfx/fxString/string_format.py
format_as_currency(number: float, decimals: int = 2, symbol: str = '$') -> str
¶
Formats a number as currency text with thousands separator.
Description
Converts a number to a formatted currency string with the given symbol, decimal places, and comma-separated thousands. Equivalent to Excel DOLLAR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number
|
float
|
The number to format. |
required |
decimals
|
int
|
Number of decimal places (default 2). |
2
|
symbol
|
str
|
Currency symbol to prepend (default '$'). |
'$'
|
Returns:
| Type | Description |
|---|---|
str
|
The formatted currency string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If number is not numeric or decimals is not an integer. |
Example
format_as_currency(1234.567) '$1,234.57' format_as_currency(1234.567, 0) '$1,235' format_as_currency(-1234.5, 2, '€') '-€1,234.50'
Complexity: O(n) where n is the number of digits.
Source code in shortfx/fxString/string_format.py
format_as_number(number: Union[int, float], decimals: int = 2, use_parens_for_negative: bool = True) -> str
¶
Format a number with thousands separators and optional parentheses for negatives.
Description
Rounds the number, adds comma thousands separators, and optionally
wraps negative values in parentheses instead of using a minus sign.
Equivalent to VBA FormatNumber.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number
|
Union[int, float]
|
Numeric value to format. |
required |
decimals
|
int
|
Number of decimal places (default 2). |
2
|
use_parens_for_negative
|
bool
|
Wrap negatives in parentheses (default True). |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted number string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If number is not numeric or decimals is not an integer. |
Example
format_as_number(1234.5678, 2) '1,234.57' format_as_number(-42.5) '(42.50)' format_as_number(-42.5, 2, False) '-42.50'
Complexity: O(1)
Source code in shortfx/fxString/string_format.py
format_as_percent(number: Union[int, float], decimals: int = 2, use_parens_for_negative: bool = True) -> str
¶
Format a number as a percentage string (multiplied by 100).
Description
Multiplies by 100, rounds to the given decimals, adds a %
suffix, and optionally uses parentheses for negatives.
Equivalent to VBA FormatPercent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number
|
Union[int, float]
|
Numeric value (0.25 → 25%). |
required |
decimals
|
int
|
Number of decimal places (default 2). |
2
|
use_parens_for_negative
|
bool
|
Wrap negatives in parentheses (default True). |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted percentage string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If number is not numeric or decimals is not an integer. |
Example
format_as_percent(0.25) '25.00%' format_as_percent(-0.1234, 1) '(12.3%)' format_as_percent(-0.1234, 1, False) '-12.3%'
Complexity: O(1)
Source code in shortfx/fxString/string_format.py
format_company_name(company_name: str | None, company_type: str | None, format_style: str) -> str | None
¶
Formats a company name by appending its type according to a specified style.
This function takes a company name and its legal type, then combines them.
It provides different formatting styles for the company type, such as enclosing
it in brackets or abbreviating it with dots. Certain administrative or
non-standard company types are handled differently, typically by appending
them after a comma. The original function included a call to an undefined
get_companyname function for these cases, which has been removed to ensure
this function's sole responsibility is formatting.
The function is case-sensitive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
company_name
|
str | None
|
The base name of the company. |
required |
company_type
|
str | None
|
The legal type of the company (e.g., 'S.L.', 'LTD'). |
required |
format_style
|
str
|
The formatting rule to apply. Expected values: 'brackets', 'dots', 'comma&dots'. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The formatted company name, or None if the input name is None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unknown format_style is provided. |
Example of use
format_company_name('My Business', 'S.L.', 'dots') -> 'My Business S.L.' format_company_name('Innovate Inc', 'INC', 'comma&dots') -> 'Innovate Inc, INC.' format_company_name('Tech Solutions', 'LTD', 'brackets') -> 'Tech Solutions (LTD)' format_company_name('City Council', 'CORPORACION LOCAL', 'dots') -> 'City Council, CORPORACION LOCAL'
Cost
The time complexity is generally O(1). However, for short company types that require dots between letters (e.g., 'SL' -> 'S.L.'), the complexity is O(K), where K is the number of characters in the company_type string, due to the string join operation.
Source code in shortfx/fxString/string_format.py
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 | |
format_date(date_input: Union[str, datetime], output_format: str = None, locale: str = 'en_US') -> str
¶
Formats a date input (string or datetime object) into a specified output format, considering the given locale for parsing string inputs and default output format.
This function accepts either a string representing a date or a datetime object. If the input is a string, it attempts to parse it using various common date formats relevant to the specified locale. It then formats the resulting datetime object into the desired output format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_input
|
Union[str, datetime]
|
The input date, which can be a string or a datetime object, to be formatted. |
required |
output_format
|
str
|
The desired output format for the date. If None, it defaults to "%Y-%m-%d" for "en_US" and "%d/%m/%Y" for "es_ES". |
None
|
locale
|
str
|
The locale to use for parsing string dates and default output format. Supported locales are "en_US" (Anglo-Saxon) and "es_ES" (European). Defaults to "en_US". |
'en_US'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted date string. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input date string cannot be parsed into a valid date for the given locale, or if an unsupported locale is provided. |
TypeError
|
If the 'date_input' type is unsupported. |
Source code in shortfx/fxString/string_format.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 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 | |
format_email_address(email_string: str) -> str
¶
Cleans an email address string by removing common typos and invalid characters.
This function sanitizes an email address string by: 1. Stripping leading and trailing whitespace. 2. Replacing multiple internal spaces with a single space. 3. Removing characters that are generally invalid in email addresses, preserving standard email characters like alphanumeric, '.', '_', '+', '-', and '@'. It does not attempt to validate the email structure, only to clean it for validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
email_string
|
str
|
The email address string to be cleaned. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The cleaned email address string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
Example of use
format_email_address(" user.name+tag@example.com ") 'user.name+tag@example.com' format_email_address("user @ domain.c@om") 'user@domain.com' format_email_address("invalid#char!@test.com") 'invalidchar@test.com'
Source code in shortfx/fxString/string_format.py
format_file_size(size_bytes: int | float, binary: bool = True) -> str
¶
Convert a byte count to a human-readable file-size string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_bytes
|
int | float
|
Number of bytes (non-negative). |
required |
binary
|
bool
|
If True use IEC binary units (KiB, MiB, …) with 1024 base; if False use SI decimal units (KB, MB, …) with 1000 base. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Human-readable string, e.g. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If size_bytes is not numeric. |
ValueError
|
If size_bytes is negative. |
Example
format_file_size(1536) '1.50 KiB' format_file_size(1500, binary=False) '1.50 KB'
Complexity: O(1)
Source code in shortfx/fxString/string_format.py
format_fullname(fullname: str | None, uppercase: bool = True) -> str | None
¶
Formats a person's full name by removing unwanted characters and normalizing spaces. Optimized with pre-compiled regex patterns and str.translate() for better performance.
This function standardizes person names by: 1. Removing or replacing special characters with spaces (optimized with translate) 2. Flattening accented vowels while preserving 'ñ', 'ç', and 'ü' 3. Removing titles (Dr, Sr, Don, Dña, Mr, Mrs, etc.) using pre-defined set 4. Normalizing spaces with pre-compiled regex 5. Converting to uppercase (optional) 6. Capitalizing each word appropriately
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fullname
|
str | None
|
The full name to format. Can be None. |
required |
uppercase
|
bool
|
If True, converts to uppercase before capitalizing. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The formatted full name in proper case, or None if input was None. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string or None. |
Example
format_fullname("josé garcía-lópez") 'Jose Garcia-Lopez' format_fullname("MARÍA DEL CARMEN") 'Maria Carmen' format_fullname("Dr. Juan Pérez") 'Juan Perez' format_fullname("SR. D. ANTONIO GARCIA") 'Antonio Garcia' format_fullname("o'connor", uppercase=False) "O'connor" format_fullname(None) None
Cost
O(n + w) where n is the length of the fullname string and w is the number of words. Optimized with str.translate() for single-pass character replacement, pre-compiled regex for whitespace normalization, and frozenset for O(1) title lookup.
Source code in shortfx/fxString/string_format.py
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 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 | |
format_internet_domain(domain_string: str) -> str
¶
Cleans and normalizes an internet domain string.
This function: 1. Strips leading/trailing whitespace. 2. Converts to lowercase (domains are case-insensitive). 3. Removes invalid characters (keeps a-z, 0-9, '-', and '.'). 4. Collapses multiple consecutive dots or hyphens. 5. Removes leading/trailing dots and hyphens. 6. Does not validate TLD or domain existence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
domain_string
|
str
|
The domain string to clean. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The cleaned and normalized domain string. |
Example
format_internet_domain(" WWW.Example--Site...COM ") 'www.example-site.com' format_internet_domain("Mi_Sitio!@#$.es") 'misitio.es'
Source code in shortfx/fxString/string_format.py
format_list_as_sentence(items: list[str], conjunction: str = 'and', separator: str = ', ') -> str
¶
Formats a list of strings as a human-readable sentence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[str]
|
The list of string items. |
required |
conjunction
|
str
|
Word placed before the last item (e.g. "and", "or", "y"). |
'and'
|
separator
|
str
|
Separator between items (default ", "). |
', '
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted string joining all items. |
Example
format_list_as_sentence(["a", "b", "c"]) 'a, b and c' format_list_as_sentence(["x", "y"], conjunction="or") 'x or y' format_list_as_sentence(["only"]) 'only'
Complexity: O(n)
Source code in shortfx/fxString/string_format.py
format_name(input_string: str, add_charset: str = '', name_type: str = 'PERSONA', shift: bool = False) -> str
¶
Description
Formats a name string by removing unwanted characters, normalizing symbols, and applying type-specific character filtering. Optimized with pre-compiled regex patterns for better performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to format. |
required |
add_charset
|
str
|
Additional characters to allow in the output. |
''
|
name_type
|
str
|
The type of name, e.g., "PERSONA" for people, determines filtering rules. |
'PERSONA'
|
shift
|
bool
|
Unused parameter, kept for compatibility. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted name string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input_string is not a string. |
Example Usage
format_name("José Pérez", "", "PERSONA") 'JOSE PEREZ' format_name("Cía. de Café S.L.", "", "EMPRESA") 'CIA DE CAFE SL'
Cost
O(n) where n is the length of input_string. Optimized with pre-compiled regex patterns and streamlined character replacement using str.translate() for single-pass processing.
Source code in shortfx/fxString/string_format.py
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 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 | |
format_number(number_input: Union[int, float, str], decimal_places: int = 2, locale: str = 'en_US', currency_symbol: str = '') -> str
¶
Formats a numeric input (int, float, or string) according to specified locale conventions.
This function provides flexible formatting for numbers, including control over decimal places, thousands separators, and optional currency symbols, based on the chosen locale (e.g., "en_US" for Anglo-Saxon, "es_ES" for European).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number_input
|
Union[int, float, str]
|
The input number, which can be an integer, float, or a string representation of a number. |
required |
decimal_places
|
int
|
The number of decimal places to include. Defaults to 2. |
2
|
locale
|
str
|
The locale for formatting conventions. Supports "en_US" (Anglo-Saxon: comma for thousands, dot for decimals) and "es_ES" (European: dot for thousands, comma for decimals). Defaults to "en_US". |
'en_US'
|
currency_symbol
|
str
|
An optional string to prepend as a currency symbol. Defaults to "". |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted number as a string. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input cannot be converted into a valid number or an unsupported locale is provided. |
TypeError
|
If the 'decimal_places' argument is not an integer. |
Source code in shortfx/fxString/string_format.py
format_number_with_negative_style(number_input: Union[int, float, str], decimal_places: int = 2, locale: str = 'en_US', currency_symbol: str = '', negative_style: str = 'minus') -> str
¶
Formats a numeric input, handling negative numbers with either a minus sign or parentheses.
This function leverages the format_number function for standard formatting
(decimal places, locale, currency) and then applies a specific style
for negative numbers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number_input
|
Union[int, float, str]
|
The number to format. |
required |
decimal_places
|
int
|
The number of decimal places. Defaults to 2. |
2
|
locale
|
str
|
The locale for formatting ("en_US" or "es_ES"). Defaults to "en_US". |
'en_US'
|
currency_symbol
|
str
|
An optional currency symbol. Defaults to "". |
''
|
negative_style
|
str
|
How to display negative numbers. Accepts "minus" (e.g., -123.45) or "parentheses" (e.g., (123.45)). Defaults to "minus". |
'minus'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted number as a string. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input cannot be converted to a number, an unsupported
locale is provided, or an invalid |
TypeError
|
If 'decimal_places' is not an integer. |
Example of use
format_number_with_negative_style(-12345.678, decimal_places=2, currency_symbol="$", negative_style="parentheses") '($12,345.68)' format_number_with_negative_style(-987.65, decimal_places=1, locale="es_ES", negative_style="minus") '-987,7' format_number_with_negative_style(5000, decimal_places=0) '5,000'
Source code in shortfx/fxString/string_format.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | |
format_url(url_string: str) -> str
¶
Cleans a URL string by removing common typos and unsafe/invalid characters.
This function sanitizes a URL string by: 1. Stripping leading and trailing whitespace. 2. Replacing multiple internal spaces with a single space. 3. Removing characters that are generally invalid or unsafe in URLs (e.g., non-ASCII characters, specific symbols that are never allowed). It preserves standard URL characters like alphanumeric, '.', '/', ':', '?', '=', '&', '-', '_', and '~'. This function focuses on cleaning the string for URL parsing, not on percent-encoding data within query parameters (which is a separate step).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url_string
|
str
|
The URL string to be cleaned. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The cleaned URL string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
Example of use
format_url(" https://www.example.com/ path with spaces?id=123 ") 'https://www.example.com/path%20with%20spaces?id=123' format_url("http://site.com/page?query=val!ue") 'http://site.com/page?query=val!ue' format_url("ftp://bad^char.com/file") 'ftp://badchar.com/file'
Source code in shortfx/fxString/string_format.py
format_with_pattern(value, pattern: str) -> str
¶
Format a numeric or date value using an Excel/VBA-style pattern.
Supports common patterns including percentage ("%"), thousands
separator ("#,##0"), fixed decimals ("0.00"), and date/time
patterns ("yyyy-mm-dd", "hh:nn:ss", etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Numeric value (int/float) or |
required | |
pattern
|
str
|
Excel/VBA format string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted string representation of value. |
Example
format_with_pattern(1234.5, "#,##0.00") '1,234.50' format_with_pattern(0.75, "0%") '75%' from datetime import datetime format_with_pattern(datetime(2025, 3, 15), "yyyy-mm-dd") '2025-03-15'
Complexity: O(n) where n is the length of pattern.
Source code in shortfx/fxString/string_format.py
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 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 | |
get_string_format(input_string: str) -> int
¶
Determines the casing format of a given string.
This function analyzes the input string to identify if it's entirely lowercase, uppercase, title-cased, capitalized, or none of these (mixed/unknown).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to analyze. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
0: None, empty, or mixed/unknown format. 1: Lowercase (e.g., "lowercase text"). 2: Capitalized (first letter uppercase, rest lowercase, e.g., "Capitalized text."). 3: Title case (first letter of each word uppercase, e.g., "An Example Title", "Word"). 4: Uppercase (e.g., "UPPERCASE TEXT"). |
Example
get_string_format("hello world") 1 get_string_format("Hello World") 3 get_string_format("HELLO WORLD") 4 get_string_format("Hello world") 2 get_string_format("MiXeD cAsE") 0 get_string_format(None) 0 get_string_format("") 0
Source code in shortfx/fxString/string_format.py
mask_data(input_string: str, mask_char: str = '*', num_chars: Optional[int] = None, position: str = 'all', start_index: int = 0, keep_visible: int = 0) -> str
¶
Mask sensitive data based on various patterns.
Description
Obfuscates parts of a string to protect sensitive information like passwords, credit card numbers, or IDs. Supports multiple masking strategies (start, end, full, or specific range).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to be masked. |
required |
mask_char
|
str
|
Character used for masking. Defaults to '*'. |
'*'
|
num_chars
|
Optional[int]
|
Total characters to obfuscate. If None, calculates based on 'position' and 'keep_visible'. |
None
|
position
|
str
|
'all' (entire string), 'start' (mask prefix), 'end' (mask suffix), or 'index' (mask range). |
'all'
|
start_index
|
int
|
Offset to start masking (only if position='index'). |
0
|
keep_visible
|
int
|
Characters to preserve (unmasked) at the end (if position='start') or start (if position='end'). |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The obfuscated string. |
Complexity
O(N) where N is the length of input_string.
Examples:
>>> mask_data("123456789", position="start", num_chars=4)
'****56789'
>>> mask_data("123456789", position="end", keep_visible=3)
'123******'
>>> mask_data("John Doe", position="index", start_index=2, num_chars=3)
'Jo***Doe'
>>> mask_data("password", mask_char="#")
'########'
Source code in shortfx/fxString/string_format.py
normalize_spaces(text: Optional[str]) -> Optional[str]
¶
Normalizes whitespace in a string: replaces multiple spaces with a single space and removes leading/trailing spaces. Optimized with pre-compiled regex pattern for better performance.
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 normalized spaces, or None if the input was None. Returns an empty string if the input was an empty string. |
Cost
O(n) where n is the length of the text. Uses pre-compiled regex pattern to avoid repeated compilation overhead.
Source code in shortfx/fxString/string_format.py
normalize_symbols(text: Optional[str]) -> Optional[str]
¶
Normalizes spacing around common symbols and punctuation marks in a string. Optimized with pre-compiled regex patterns for better performance.
This function applies the following rules: 1. Removes spaces around symbols that typically 'stick' to words/numbers (e.g., @, (), [], {}, <>, #, /, \, |, _, -, ?, !, ¡, º, ª). 2. Ensures a space AFTER punctuation that typically requires it (e.g., ., ,, :, ;). 3. Ensures a single space AROUND operators (e.g., +, =, &). 4. Removes space BEFORE currency symbols (e.g., $, €). 5. Finally, normalizes all remaining multiple spaces to single spaces.
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 normalized symbols and spaces, or None if the input was None. Returns an empty string if the input was an empty string. |
Cost
O(n) where n is the length of the text. Optimized with pre-compiled regex patterns to eliminate repeated pattern compilation overhead.
Source code in shortfx/fxString/string_format.py
normalize_text(text: str) -> str
¶
Normalizes text by removing accents and converting to lowercase.
This function strips diacritical marks (e.g., 'á' becomes 'a') to ensure consistent comparison keys for spellchecking algorithms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to normalize. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The normalized, lowercase ASCII string. |
Example
normalize_text("Julián") 'julian'
Source code in shortfx/fxString/string_format.py
numbers_from_string(input_string: str, separator: str = '') -> Optional[str]
¶
Extracts all numerical sequences from a given string and returns them as a single string.
This function uses regular expressions to find all occurrences of integers or floating-point numbers within the input string. It then joins these numbers together using an optional separator to form a single output string. If no numbers are found, or the input string is empty, it returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string from which to extract numbers. |
required |
separator
|
str
|
The string to use to join the extracted numbers. Defaults to an empty string, meaning numbers will be concatenated directly. |
''
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
A single string containing all the numbers found in the input string, |
Optional[str]
|
joined by the specified separator. Returns None if no numbers are found |
Optional[str]
|
or the input string is empty. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input 'input_string' is not a string. |
Example of use
numbers_from_string("The price is $12.99 with 5% tax.") "12.995"
numbers_from_string("Item ID: 12345, Quantity: 7", separator="-") "12345-7"
numbers_from_string("No numbers here.") None
numbers_from_string("") None
numbers_from_string("Measurement: -10.5 meters and 20 degrees.", separator=", ") "-10.5, 20"
Source code in shortfx/fxString/string_format.py
pad_string(text: str, length: int, char: str = ' ', direction: str = 'right') -> str
¶
Rellena una cadena de texto hasta una longitud específica con un carácter dado.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
La cadena de texto a rellenar. |
required |
length
|
int
|
La longitud total deseada de la cadena resultante. |
required |
char
|
str
|
El carácter con el que se rellenará la cadena. Debe ser un solo carácter. Por defecto es un espacio (' '). |
' '
|
direction
|
str
|
La dirección del relleno. Puede ser 'left' (izquierda) o 'right' (derecha). Por defecto es 'right'. |
'right'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
La cadena rellenada hasta la longitud especificada. Si la cadena original ya es igual o más larga que la longitud deseada, se devolverá la cadena original truncada a la longitud si es más larga. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Si 'char' no es un solo carácter o 'direction' no es 'left' o 'right'. |
Source code in shortfx/fxString/string_format.py
parse_company(company_name: str, legal_forms_set_override: set = None) -> list
¶
Description
Separates the company name from its legal form, handling malformed formats and edge cases. Prioritizes longer legal forms, normalizes input, and ensures robust matching using regular expressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
company_name
|
str
|
The full company name (e.g., "Acme Corp Ltd"). |
required |
legal_forms_set_override
|
set
|
A set of legal forms to search. If None, uses the global LEGAL_FORMS_SET. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
[company_name_only, canonical_legal_form]. If no legal form is found, returns [original_company_name, None]. |
Example Usage
parse_company("PESCANOVA S.A.", {"SA"}) ['PESCANOVA', 'SA'] parse_company("Acme Corp Ltd.", {"LTD"}) ['Acme Corp', 'LTD'] parse_company("No Legal Form Company") ['No Legal Form Company', None]
Cost
O(M log M + M * N * K), where M is the number of legal forms, N is the string length, and K is regex complexity.
Source code in shortfx/fxString/string_format.py
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 1850 1851 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 | |
pluralize_count(count: int, singular: str, plural: Optional[str] = None) -> str
¶
Returns a count with its noun in singular or plural form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
The numeric quantity. |
required |
singular
|
str
|
The singular noun (e.g. "item"). |
required |
plural
|
Optional[str]
|
The plural noun. If omitted, appends "s" to singular. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted string like |
Example
pluralize_count(1, "item") '1 item' pluralize_count(5, "item") '5 items' pluralize_count(2, "child", "children") '2 children'
Complexity: O(1)
Source code in shortfx/fxString/string_format.py
remove_numbers_from_string(input_string: str) -> str
¶
Removes all numerical digits and decimal points from a given string.
This function uses regular expressions to find and remove all occurrences of digits (0-9) and periods (which are often part of numbers, e.g., '3.14'). It returns the modified string with numbers removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string from which to remove numbers. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A new string with all numerical digits and decimal points removed. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input 'input_string' is not a string. |
Example of use
remove_numbers_from_string("The price is $12.99 with 5% tax.") "The price is $ with % tax."
remove_numbers_from_string("Item ID: 12345, Quantity: 7") "Item ID: , Quantity: "
remove_numbers_from_string("No numbers here.") "No numbers here."
remove_numbers_from_string("") ""
Source code in shortfx/fxString/string_format.py
reorder_comma_fullname(name_with_surname: str) -> str
¶
Reformats a name string from 'Surname, Name' to 'Name Surname'.
This function takes a string where the surname is followed by a comma and then the first name. It splits the string at the comma and rearranges the parts to return the first name followed by the surname.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_with_surname
|
str
|
The input string in 'Surname, Name' format. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The reformatted name string in 'Name Surname' format. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input string does not contain a comma. |
Example of use
reorder_comma_fullname("Doe, John") 'John Doe'
Source code in shortfx/fxString/string_format.py
rot13(text: str) -> str
¶
Applies the ROT13 substitution cipher to a string.
Each letter is shifted by 13 positions in the alphabet. Applying ROT13 twice returns the original text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The ROT13-encoded string. |
Example
rot13("Hello") 'Uryyb' rot13("Uryyb") 'Hello'
Complexity: O(n)
Source code in shortfx/fxString/string_format.py
snake_to_camel(text: str, pascal: bool = False) -> str
¶
Converts a snake_case string to camelCase (or PascalCase).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The snake_case string. |
required |
pascal
|
bool
|
If True, returns PascalCase (first letter uppercase). Defaults to False (camelCase). |
False
|
Returns:
| Type | Description |
|---|---|
str
|
The camelCase or PascalCase equivalent. |
Example
snake_to_camel("snake_case") 'snakeCase' snake_to_camel("hello_world", pascal=True) 'HelloWorld' snake_to_camel("already") 'already' snake_to_camel("get_http_response") 'getHttpResponse'
Complexity: O(n)
Source code in shortfx/fxString/string_format.py
sql_quote(sql_string: str, db_type: str) -> str
¶
Escapes single quotes in a SQL string based on the database type.
This function prevents SQL injection by properly escaping single quotes within a given SQL string. Different database systems handle quote escaping differently (e.g., SQLite and Oracle use two single quotes, while others might use a backslash).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql_string
|
str
|
The SQL string that needs to have its quotes escaped. |
required |
db_type
|
str
|
The type of the database ('sqlite', 'oracle', or others). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The SQL string with single quotes properly escaped for the specified database type. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If db_type is not a string. |
Example
sql_quote("SELECT * FROM users WHERE name = 'O''Reilly'", "sqlite") "SELECT * FROM users WHERE name = ''O''''Reilly''" sql_quote("INSERT INTO products (name) VALUES ('Laptop')", "postgresql") "INSERT INTO products (name) VALUES (''Laptop''')"
Source code in shortfx/fxString/string_format.py
string_aZ(input_string)
¶
Feature Description: Filters a string to keep only alphabetic characters (a-z, A-Z). Optimized with pre-compiled regex pattern for better performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to filter. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
A new string containing only alphabetic characters from the input. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
Usage Example: string_aZ("Hola Mundo 123!") returns "HolaMundo"
Cost
O(n) where n is the length of input_string. Uses pre-compiled regex pattern.
Source code in shortfx/fxString/string_format.py
string_aZ09(input_string)
¶
Feature Description: Filters a string to keep only alphanumeric characters (a-z, A-Z, 0-9). Optimized with pre-compiled regex pattern for better performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to filter. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
A new string containing only alphanumeric characters from the input. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
Usage Example: string_aZ09("Hola Mundo 123!") returns "HolaMundo123"
Cost
O(n) where n is the length of input_string. Uses pre-compiled regex pattern.
Source code in shortfx/fxString/string_format.py
string_aZ09_plus(input_string, additional_charset='')
¶
Filters a string to keep only alphanumeric characters (a-z, A-Z, 0-9) and any characters provided in an additional charset.
This function leverages regular expressions for efficient character filtering, allowing for a highly customizable set of allowed characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to filter. |
required |
additional_charset
|
str
|
An optional string containing additional characters to allow in the filtered output. Defaults to an empty string, meaning only alphanumeric characters are kept. |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
A new string containing only alphanumeric characters and characters from the additional_charset. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input_string is not a string. |
Usage Example
Example 1: Basic alphanumeric filtering¶
string_aZ09_plus("Hello World 123!") # Returns "HelloWorld123"
Example 2: Filtering with an additional charset for spaces and hyphens¶
string_aZ09_plus("This-is a test!", " -") # Returns "This-is a test"
Cost
The time complexity of this function is O(n), where n is the length of the input_string, due to the regular expression substitution operation. The compilation of the regex is O(m), where m is the length of the regex pattern, which is constant for repeated calls.
Source code in shortfx/fxString/string_format.py
string_aZ_plus(input_string, additional_charset='')
¶
Filters a string to keep only alphabetic characters (a-z, A-Z) and any characters provided in an additional charset.
This function utilizes regular expressions for efficient character filtering, allowing for a highly customizable set of allowed characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_string
|
str
|
The string to filter. |
required |
additional_charset
|
str
|
An optional string containing additional characters to allow in the filtered output. Defaults to an empty string, meaning only alphabetic characters are kept. |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
A new string containing only alphabetic characters and characters from the additional_charset. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input_string is not a string. |
Usage Example
Example 1: Basic alphabetic filtering¶
string_aZ_plus("Hello World 123!") # Returns "HelloWorld"
Example 2: Filtering with an additional charset for spaces and hyphens¶
string_aZ_plus("This-is a test!", " -") # Returns "This-isatest"
Cost
The time complexity of this function is O(n), where n is the length of the input_string, due to the regular expression substitution operation. The compilation of the regex is O(m), where m is the length of the regex pattern, which is constant for repeated calls.
Source code in shortfx/fxString/string_format.py
swap_case(text: Optional[str]) -> Optional[str]
¶
Inverts the case of every character in a string.
Uppercase becomes lowercase and vice versa.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
The input string. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The string with swapped case, or None if input is None. |
Example
swap_case("Hello World") 'hELLO wORLD' swap_case("PyThOn") 'pYtHoN'
Complexity: O(n)
Source code in shortfx/fxString/string_format.py
to_lower(text: Optional[str]) -> Optional[str]
¶
Convierte una cadena de texto a minúsculas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
La cadena de texto de entrada. Puede ser None. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: La cadena convertida a minúsculas, o None si la entrada fue None. Si la entrada es una cadena vacía, devuelve una cadena vacía. |
Source code in shortfx/fxString/string_format.py
to_upper(text: Optional[str]) -> Optional[str]
¶
Convierte una cadena de texto a mayúsculas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
La cadena de texto de entrada. Puede ser None. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: La cadena convertida a mayúsculas, o None si la entrada fue None. Si la entrada es una cadena vacía, devuelve una cadena vacía. |
Source code in shortfx/fxString/string_format.py
word_wrap(text: str, width: int = 80) -> str
¶
Wraps text to a specified line width, breaking at word boundaries.
Long words that exceed width are kept intact on their own line (no mid-word breaks).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text to wrap. |
required |
width
|
int
|
Maximum number of characters per line. Defaults to 80. |
80
|
Returns:
| Type | Description |
|---|---|
str
|
The wrapped text with newline separators. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If width is less than 1. |
Example
word_wrap("The quick brown fox jumps over the lazy dog", 20) 'The quick brown fox\njumps over the lazy\ndog' word_wrap("short", 80) 'short'
Complexity: O(n)
Source code in shortfx/fxString/string_format.py
zfill(text: str, width: int) -> str
¶
Pads a string with leading zeros to fill a given width.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string. |
required |
width
|
int
|
The minimum total width of the result. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The zero-padded string. |
Example
zfill("42", 5) '00042' zfill("hello", 3) 'hello'
Complexity: O(width)