You can download this code by clicking the button below.
This code is now available for download.
This function formats a string by line count. If a single line exceeds the specified maximum length, it is split into multiple lines.
Technology Stack : String manipulation
Code Type : String formatting function
Code Difficulty : Intermediate
def format_string(input_string, max_length=50):
if not isinstance(input_string, str):
raise ValueError("input_string must be a string")
if max_length <= 0:
raise ValueError("max_length must be a positive integer")
lines = input_string.splitlines()
formatted_lines = []
for line in lines:
if len(line) <= max_length:
formatted_lines.append(line)
else:
for i in range(0, len(line), max_length):
formatted_lines.append(line[i:i+max_length])
return "\n".join(formatted_lines)