str Module (stx.str)
scitex-str: Text processing utilities for scientific workflows.
- exception scitex.str.LaTeXFallbackError[source]
Bases:
ExceptionRaised when LaTeX fallback mechanisms fail.
- scitex.str.add_hat_in_latex_style(str_or_num)[source]
Add LaTeX hat notation to string.
- Parameters:
str_or_num (str or numeric) – Input to format with hat notation
- Returns:
LaTeX-formatted string with hat notation
- Return type:
Examples
>>> add_hat_in_latex_style('aaa') '$\hat{aaa}$'
>>> add_hat_in_latex_style('x') '$\hat{x}$'
>>> add_hat_in_latex_style(1) '$\hat{1}$'
- scitex.str.auto_factor_axis(ax, axis='both', precision=2, min_factor_power=3, return_latex=True, return_unicode=False, label_offset=(0.02, 0.98))[source]
Automatically factor out common powers of 10 from axis tick labels.
- Parameters:
ax (matplotlib.axes.Axes) – The axes object to modify
axis (
str) – Which axis to factor (‘x’, ‘y’, or ‘both’), by default ‘both’precision (
int) – Number of decimal places in factored values, by default 2min_factor_power (
int) – Minimum power of 10 to factor out, by default 3return_latex (
bool) – Use LaTeX format for factor string, by default Truereturn_unicode (
bool) – Use Unicode superscripts for factor string, by default Falselabel_offset (
Tuple[float,float]) – Position for factor label as (x, y) in axes coordinates, by default (0.02, 0.98)
- Return type:
Examples
>>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> ax.plot([1000, 2000, 3000], [0.001, 0.002, 0.003]) >>> auto_factor_axis(ax, axis='both')
- scitex.str.axis_label(label, unit=None, **kwargs)[source]
Convenient alias for format_axis_label.
- Return type:
- scitex.str.check_latex_capability()[source]
Check if LaTeX rendering is available and working.
- Returns:
True if LaTeX is available, False otherwise
- Return type:
- scitex.str.check_unit_consistency(x_unit=None, y_unit=None, operation='none')[source]
Check unit consistency for mathematical operations.
- Parameters:
- Returns:
(is_consistent, expected_result_unit)
- Return type:
Examples
>>> check_unit_consistency("m", "s", "divide") (True, 'm/s')
>>> check_unit_consistency("m", "m", "add") (True, 'm')
>>> check_unit_consistency("m", "kg", "add") (False, 'Units incompatible for addition')
- scitex.str.clean_path(path_string)[source]
Cleans and normalizes a file system path string.
Example
>>> clean('/home/user/./folder/../file.txt') '/home/user/file.txt' >>> clean('path/./to//file.txt') 'path/to/file.txt'
- scitex.str.color_text(text, c='green')[source]
Apply ANSI color codes to text.
- Parameters:
- Returns:
The input text with ANSI color codes applied.
- Return type:
Example
>>> print(color_text("Hello, World!", "blue")) # This will print "Hello, World!" in blue text
- scitex.str.ct(text, c='green')
Apply ANSI color codes to text.
- Parameters:
- Returns:
The input text with ANSI color codes applied.
- Return type:
Example
>>> print(color_text("Hello, World!", "blue")) # This will print "Hello, World!" in blue text
- scitex.str.decapitalize(input_string)[source]
Converts first character of string to lowercase.
Example
>>> decapitalize("Hello") 'hello' >>> decapitalize("WORLD") 'wORLD' >>> decapitalize("") ''
- scitex.str.disable_latex_fallback()[source]
Disable LaTeX fallback (force LaTeX usage).
- Return type:
- scitex.str.enable_latex_fallback(mode='auto')[source]
Enable LaTeX fallback with specified mode.
- Return type:
- scitex.str.factor_out_digits(values, precision=2, min_factor_power=3, return_latex=True, return_unicode=False)[source]
Factor out common powers of 10 from numerical values for cleaner scientific notation.
- Parameters:
values (
Union[List,ndarray,float,int]) – Numerical values to factorprecision (
int) – Number of decimal places in factored values, by default 2min_factor_power (
int) – Minimum power of 10 to factor out, by default 3return_latex (
bool) – Return factor string in LaTeX format, by default Truereturn_unicode (
bool) – Return factor string with Unicode superscripts, by default False
- Returns:
Tuple of (factored_values, factor_string)
- Return type:
Examples
>>> factor_out_digits([1000, 2000, 3000]) ([1.0, 2.0, 3.0], '$\times 10^{3}$')
>>> factor_out_digits([0.001, 0.002, 0.003]) ([1.0, 2.0, 3.0], '$\times 10^{-3}$')
>>> factor_out_digits([1.5e6, 2.3e6, 4.1e6]) ([1.5, 2.3, 4.1], '$\times 10^{6}$')
- scitex.str.format_axis_label(label, unit=None, unit_style='parentheses', capitalize=True, latex_math=True, enable_fallback=True, replace_underscores=True)[source]
Format axis labels with proper unit handling.
- Parameters:
label (
str) – The variable name or descriptionunit_style (
str) – Unit bracket style, by default “parentheses”capitalize (
bool) – Whether to capitalize, by default Truelatex_math (
bool) – Whether to enable LaTeX math, by default Trueenable_fallback (
bool) – Whether to enable LaTeX fallback mechanisms, by default Truereplace_underscores (
bool) – Whether to replace underscores with spaces, by default True
- Returns:
Formatted axis label with automatic LaTeX fallback
- Return type:
Examples
>>> format_axis_label("time", "s") 'Time (s)'
>>> format_axis_label("voltage", "V", unit_style="brackets") 'Voltage [V]'
>>> format_axis_label("temperature", "°C") 'Temperature (°C)'
>>> format_axis_label("signal_power", "dB") 'Signal Power (dB)'
- scitex.str.format_plot_text(text, capitalize=True, unit_style='parentheses', latex_math=True, scientific_notation=True, enable_fallback=True, replace_underscores=True)[source]
Format text for scientific plots with proper conventions and LaTeX fallback.
- Parameters:
text (
str) – Input text to formatcapitalize (
bool) – Whether to capitalize the first letter, by default Trueunit_style (
str) – Unit bracket style: “parentheses” (), “brackets” [], or “auto”, by default “parentheses”latex_math (
bool) – Whether to enable LaTeX math formatting, by default Truescientific_notation (
bool) – Whether to format scientific notation properly, by default Trueenable_fallback (
bool) – Whether to enable LaTeX fallback mechanisms, by default Truereplace_underscores (
bool) – Whether to replace underscores with spaces, by default True
- Returns:
Formatted text ready for matplotlib with automatic LaTeX fallback
- Return type:
Examples
>>> format_plot_text("time (s)") 'Time (s)'
>>> format_plot_text("voltage [V]", unit_style="brackets") 'Voltage [V]'
>>> format_plot_text("frequency in Hz", unit_style="auto") 'Frequency (Hz)'
>>> format_plot_text("signal_power_db") 'Signal Power Db'
>>> format_plot_text(r"$lpha$ decay") # Falls back if LaTeX fails 'α decay'
Notes
If LaTeX rendering fails, this function automatically falls back to mathtext or unicode alternatives while preserving scientific formatting.
- scitex.str.format_title(title, subtitle=None, capitalize=True, latex_math=True, enable_fallback=True, replace_underscores=True)[source]
Format plot titles with proper conventions.
- Parameters:
title (
str) – Main title textcapitalize (
bool) – Whether to capitalize, by default Truelatex_math (
bool) – Whether to enable LaTeX math, by default Trueenable_fallback (
bool) – Whether to enable LaTeX fallback mechanisms, by default Truereplace_underscores (
bool) – Whether to replace underscores with spaces, by default True
- Returns:
Formatted title with automatic LaTeX fallback
- Return type:
Examples
>>> format_title("neural spike analysis") 'Neural Spike Analysis'
>>> format_title("data analysis", "preliminary results") 'Data Analysis\nPreliminary Results'
>>> format_title("signal_processing_results") 'Signal Processing Results'
- scitex.str.grep(str_list, search_key)[source]
Search for a key in a list of strings and return matching items.
- Parameters:
- Returns:
A list of strings from str_list that contain the search_key.
- Return type:
Example
>>> grep(['apple', 'banana', 'cherry'], 'a') ['apple', 'banana'] >>> grep(['cat', 'dog', 'elephant'], 'e') ['elephant']
- scitex.str.hat_latex_style(str_or_num)
Add LaTeX hat notation to string.
- Parameters:
str_or_num (str or numeric) – Input to format with hat notation
- Returns:
LaTeX-formatted string with hat notation
- Return type:
Examples
>>> add_hat_in_latex_style('aaa') '$\hat{aaa}$'
>>> add_hat_in_latex_style('x') '$\hat{x}$'
>>> add_hat_in_latex_style(1) '$\hat{1}$'
- scitex.str.latex_fallback_decorator(fallback_strategy='auto', preserve_math=True)[source]
Decorator to add LaTeX fallback capability to functions.
- scitex.str.latex_style(str_or_num)
Convert string or number to LaTeX math mode format.
- Parameters:
str_or_num (str or numeric) – Input to format in LaTeX style
- Returns:
LaTeX-formatted string wrapped in $…$
- Return type:
Examples
>>> to_latex_style('aaa') '$aaa$'
>>> to_latex_style('x^2') '$x^2$'
>>> to_latex_style(123) '$123$'
- scitex.str.latex_to_mathtext(latex_str)[source]
Convert LaTeX syntax to matplotlib mathtext equivalent.
- scitex.str.parse(string_or_fstring, fstring_or_string)[source]
Bidirectional parser that attempts parsing in both directions.
- Parameters:
- Returns:
Parsed dictionary or formatted string
- Return type:
- Raises:
ValueError – If parsing fails in both directions
Examples
>>> # Forward parsing >>> parse("./data/Patient_23_002", "./data/Patient_{id}") {'id': '23_002'}
>>> # Reverse parsing >>> parse("./data/Patient_{id}", "./data/Patient_23_002") {'id': '23_002'}
- scitex.str.print_debug()[source]
Print a prominent debug mode banner.
Displays a highly visible yellow banner to indicate that the program is running in debug mode. Useful for making debug runs immediately distinguishable from production runs.
The banner consists of multiple lines of exclamation marks with “DEBUG MODE” prominently displayed in the center.
Examples
>>> # At the start of debug runs >>> if DEBUG: ... print_debug() !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!! DEBUG MODE !!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
>>> # In configuration validation >>> if config.debug_mode: ... print_debug() ... print("Debug logging enabled")
See also
printcColored printing function used internally
Notes
The banner is printed in yellow color to ensure high visibility in terminal output.
- scitex.str.printc(message, c='blue', char='-', n=40)[source]
Print a message surrounded by a character border.
This function prints a given message surrounded by a border made of a specified character. The border can be colored if desired.
- Parameters:
message (str) – The message to be printed inside the border.
char (str, optional) – The character used to create the border (default is “-“).
n (int, optional) – The width of the border (default is 40).
c (str, optional) – The color of the border. Can be ‘red’, ‘green’, ‘yellow’, ‘blue’, ‘magenta’, ‘cyan’, ‘white’, or ‘grey’ (default is None, which means no color).
- Return type:
None
Example
>>> print_block("Hello, World!", char="*", n=20, c="blue") ******************** * Hello, World! * ********************
Note: The actual output will be in green color.
- scitex.str.readable_bytes(num, suffix='B')[source]
Convert a number of bytes to a human-readable format.
- Parameters:
- Returns:
A human-readable string representation of the byte size.
- Return type:
Example
>>> readable_bytes(1024) '1.0 KiB' >>> readable_bytes(1048576) '1.0 MiB' >>> readable_bytes(1073741824) '1.0 GiB'
- scitex.str.remove_ansi(string)[source]
Removes ANSI escape sequences from a given text chunk.
Parameters: - chunk (str): The text chunk to be cleaned.
Returns: - str: The cleaned text chunk.
- scitex.str.replace(string, replacements=None)[source]
Replace placeholders in the string with corresponding values from replacements.
This function replaces placeholders in the format {key} within the input string with corresponding values from the replacements dictionary. If replacements is a string, it replaces the entire input string.
- Parameters:
- Returns:
The input string with placeholders replaced by their corresponding values
- Return type:
Examples
>>> replace("Hello, {name}!", {"name": "World"}) 'Hello, World!' >>> replace("Original string", "New string") 'New string' >>> replace("Value: {x}", {"x": "42"}) 'Value: 42' >>> template = "Hello, {name}! You are {age} years old." >>> replacements = {"name": "Alice", "age": "30"} >>> replace(template, replacements) 'Hello, Alice! You are 30 years old.'
- scitex.str.safe_add_hat_in_latex_style(str_or_num)
Add LaTeX hat notation to string.
- Parameters:
str_or_num (str or numeric) – Input to format with hat notation
- Returns:
LaTeX-formatted string with hat notation
- Return type:
Examples
>>> add_hat_in_latex_style('aaa') '$\hat{aaa}$'
>>> add_hat_in_latex_style('x') '$\hat{x}$'
>>> add_hat_in_latex_style(1) '$\hat{1}$'
- scitex.str.safe_latex_render(text, fallback_strategy='auto', preserve_math=True)[source]
Safely render LaTeX text with automatic fallback.
- scitex.str.safe_to_latex_style(str_or_num)
Convert string or number to LaTeX math mode format.
- Parameters:
str_or_num (str or numeric) – Input to format in LaTeX style
- Returns:
LaTeX-formatted string wrapped in $…$
- Return type:
Examples
>>> to_latex_style('aaa') '$aaa$'
>>> to_latex_style('x^2') '$x^2$'
>>> to_latex_style(123) '$123$'
- scitex.str.scientific_text(text, **kwargs)[source]
Convenient alias for format_plot_text with scientific defaults.
- Return type:
- scitex.str.search(patterns, strings, only_perfect_match=False, as_bool=False, ensure_one=False)[source]
Search for patterns in strings using regular expressions.
- Parameters:
patterns (str or list of str) – The pattern(s) to search for. Can be a single string or a list of strings.
strings (str or list of str) – The string(s) to search in. Can be a single string or a list of strings.
only_perfect_match (bool, optional) – If True, only exact matches are considered (default is False).
as_bool (bool, optional) – If True, return a boolean array instead of indices (default is False).
ensure_one (bool, optional) – If True, ensures only one match is found (default is False).
- Returns:
A two-element tuple. Its shape depends on
as_bool:as_bool=Falsereturns(list[int], list[str])— the indices where matches were found, and the matched strings.as_bool=Truereturns(numpy.ndarray[bool], list[str])— a boolean mask the same length asstrings, and the matched strings.
- Return type:
Example
>>> patterns = ['orange', 'banana'] >>> strings = ['apple', 'orange', 'apple', 'apple_juice', 'banana', 'orange_juice'] >>> search(patterns, strings) ([1, 4, 5], ['orange', 'banana', 'orange_juice'])
>>> patterns = 'orange' >>> strings = ['apple', 'orange', 'apple', 'apple_juice', 'banana', 'orange_juice'] >>> search(patterns, strings) ([1, 5], ['orange', 'orange_juice'])
- scitex.str.smart_tick_formatter(values, max_ticks=6, factor_out=True, precision=2, min_factor_power=3, return_latex=True)[source]
Smart tick formatter that combines nice tick selection with factor-out-digits.
- Parameters:
values (
Union[List,ndarray]) – Data values to create ticks formax_ticks (
int) – Maximum number of ticks, by default 6factor_out (
bool) – Whether to factor out common powers of 10, by default Trueprecision (
int) – Number of decimal places, by default 2min_factor_power (
int) – Minimum power to factor out, by default 3return_latex (
bool) – Use LaTeX format, by default True
- Returns:
(tick_positions, tick_labels, factor_string)
- Return type:
Examples
>>> smart_tick_formatter([1000, 1500, 2000, 2500, 3000]) ([1000, 1500, 2000, 2500, 3000], ['1.0', '1.5', '2.0', '2.5', '3.0'], '$\times 10^{3}$')
- scitex.str.squeeze_spaces(string, pattern=' +', repl=' ')[source]
Replace multiple occurrences of a pattern in a string with a single replacement.
- Parameters:
- Returns:
The processed string with pattern occurrences replaced.
- Return type:
Example
>>> squeeze_spaces("Hello world") 'Hello world' >>> squeeze_spaces("a---b--c-d", pattern="-+", repl="-") 'a-b-c-d'
- scitex.str.title_case(text)[source]
Convert a string to title case.
Keeps certain prepositions, conjunctions, and articles in lowercase, and ensures words detected as potential acronyms (all uppercase) are fully capitalized.
- Parameters:
text (str) – The text to convert to title case.
- Returns:
The converted text in title case with certain words in lowercase and potential acronyms fully capitalized.
- Return type:
Examples
>>> title_case("welcome to the world of ai and using CPUs for gaming") 'Welcome to the World of AI and Using CPUs for Gaming'
- scitex.str.to_latex_style(str_or_num)[source]
Convert string or number to LaTeX math mode format.
- Parameters:
str_or_num (str or numeric) – Input to format in LaTeX style
- Returns:
LaTeX-formatted string wrapped in $…$
- Return type:
Examples
>>> to_latex_style('aaa') '$aaa$'
>>> to_latex_style('x^2') '$x^2$'
>>> to_latex_style(123) '$123$'