Skip to content

Instantly share code, notes, and snippets.

@ichux
Last active November 3, 2025 09:26
Show Gist options
  • Select an option

  • Save ichux/9ea66fa005f326d67d8b14912c4543fc to your computer and use it in GitHub Desktop.

Select an option

Save ichux/9ea66fa005f326d67d8b14912c4543fc to your computer and use it in GitHub Desktop.
import textwrap
def format_string(data, chunk_size=73, indent=4, return_output=False):
"""
Format a string into chunks of specified size using textwrap, with optional indentation.
Args:
data: Input string to be formatted.
chunk_size: Size of each chunk (default: 73).
indent: Number of spaces for indentation (default: 4).
return_output: If True, return the formatted string instead of printing (default: False).
Returns:
If return_output is True, returns the formatted string; otherwise, None.
Raises:
TypeError: If data is not a string.
"""
if not isinstance(data, str):
raise TypeError("Input 'data' must be a string")
if not data:
result = "= ()"
if return_output:
return result
print(result)
return
# Split the string into chunks using textwrap
chunks = textwrap.wrap(data, width=chunk_size, replace_whitespace=False, drop_whitespace=False)
# Format the output
indent_str = " " * indent
formatted_chunks = f'"\n{indent_str}"'.join(chunks)
result = f"= (\n{indent_str}\"{formatted_chunks}\"\n)"
if return_output:
return result
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment