2

I am using python to generate a test file used for programming. In this file, I have several auto-generated comments. Problem is, some of these comments can be quite long, and the software which reads the file generates an error if a line is too long.

What I am looking for is a method of breaking a string with '\n# '. The location of these line returns should limit the width of any one line to be less than a certain width. Below is an example of what I want to do. I need code that generates "broken_line" from "long_line".

long_line = "# alpha || bravo || charlie || delta || echo are the first 5 elements of NATO"

broken_line = "# alpha || bravo || charlie ||\n# delta || echo are the first \n# 5 elements of NATO"


>>>print long_line
# alpha || bravo || charlie || delta || echo are the first 5 elements of NATO

>>>print broken_line
# alpha || bravo || charlie ||
# delta || echo are the first
# 5 elements of NATO

2 Answers 2

7

Use the textwrap module to wrap lines to a maximum width. You can specify '# ' as indentation to prefix your lines properly:

>>> import textwrap
>>> long_line = "# alpha || bravo || charlie || delta || echo are the first 5 elements of NATO"
>>> textwrap.fill(long_line, 30, subsequent_indent='# ')
'# alpha || bravo || charlie ||\n# delta || echo are the first\n# 5 elements of NATO'
>>> print textwrap.fill(long_line, 30, subsequent_indent='# ')
# alpha || bravo || charlie ||
# delta || echo are the first
# 5 elements of NATO

The module is very flexible, do read the documentation to see what knobs you want to twiddle for the perfect result.

Sign up to request clarification or add additional context in comments.

1 Comment

That is a very nice module and it did exactly what I was looking for. Thank you!
1

One approach is to use the textwrap-module

In [6]: import textwrap

In [7]: long_line = "# alpha || bravo || charlie || delta || echo are the first 5 elements of NATO"

In [8]: textwrap.wrap(long_line, width=50)
Out[8]: 
['# alpha || bravo || charlie || delta || echo are',
 'the first 5 elements of NATO']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.