To split text in Python for formatting code purposes, you can use several built-in tools and functions depending on how you want to split the text. Below are some common techniques:
🔹 1. Splitting by Whitespace or New Lines
Useful when parsing or formatting code based on line breaks or indentation.
text = "def greet():\n print('Hello')\n print('World')"
lines = text.split('\n') # Split by newline
for line in lines:
print(f"LINE: {line}")
🔹 2. Splitting by Specific Delimiters
Split by characters like ,, :, = etc., commonly used in code.
assignment = "x = 42"
parts = assignment.split('=')
print(parts) # ['x ', ' 42']
You can also .strip() the parts to clean up whitespace:
parts = [part.strip() for part in assignment.split('=')]
print(parts) # ['x', '42']
🔹 3. Using re.split() for Advanced Splitting
Regex allows flexible splitting based on patterns.
import re
code = "int a = 5; float b = 6.0;"
statements = re.split(r'[;]+', code)
print([s.strip() for s in statements if s.strip()])
🔹 4. Using textwrap to Split or Format Code for Display
Helpful when displaying code snippets in narrow formats like console UI.
import textwrap
code = "def long_function_name(var_one, var_two, var_three): return var_one + var_two + var_three"
wrapped = textwrap.wrap(code, width=50)
print("\n".join(wrapped))
🔹 5. Line-by-Line Parsing for Analysis or Transformation
This approach is good when reformatting or analyzing code syntactically.
code_snippet = """
def add(a, b):
return a + b
"""
lines = code_snippet.strip().splitlines()
for i, line in enumerate(lines):
indent = len(line) - len(line.lstrip())
print(f"Line {i+1} (Indent {indent}): {line.strip()}")
✅ Example Use Case: Formatting Code Snippet in Markdown
code = '''
def greet(name):
print(f"Hello, {name}")
'''
formatted = '\n'.join(f" {line}" for line in code.strip().splitlines())
print("```python\n" + formatted + "\n```")
Let me know your exact use case (e.g. formatting Python code, parsing into AST, preparing text for display) — I can tailor the solution better for that!