Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7971255
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:35:41+00:00 2026-06-04T07:35:41+00:00

Ok so I’m trying to take an input text file and justify it like

  • 0

Ok so I’m trying to take an input text file and justify it like microsoft word or any other word processor would. I’ve have gotten the text to do character justification bar the last line. I’m trying to figure out how to iterate over each space in the last line and insert a ' ' to get the last last up to the specified length.

If I try:

for ' ' in new:
    insert(new,' ',find(' '))

In the spirit of simple style that python has taught me,
I get a non iterable error. Hence the while in the code loop. But this only inserts all the spaces at the first space.

Also is there a way to get this program to justified by words and not chars?

I was using the ‘Lorem ipsum…’ paragraph as my default text.

Any help is appreciated.

full code:

inf = open('filein.txt', 'r')
of = open('fileout.txt', 'w')

inf.tell()

n = input('enter the number of characters per line: ')

def insert(original, new, pos):
  #Inserts new inside original at pos.
  return original[:pos] + new + original[pos:] 

try:
    print 'you entered {}\n'.format(int(n))
except:
    print 'there was an error'
    n = input('enter the number of characters per line: ')
else:
    new = inf.readline(n)
    def printn(l):

        print>>of, l+'\n'
        print 'printing to file',
        print '(first char: {} || last char: {})'.format(l[0],l[-1])

    while new != '': #multiple spaces present at EOF
        if new[0] != ' ': #check space at beginning of line
            if new[-1] != ' ': # check space at end of line
                while (len(new) < n):
                    new = insert(new,' ',(new.find(' ')))
                printn(new)

        elif new[0] == ' ':
            new = new.lstrip() #remove leading whitespace
            new = insert(new,' ',(new.find(' ')))
            while (len(new) < n):
                new = insert(new,' ',(new.find(' ')))
            printn(new)

        elif new[-1] == ' ':
            new = new.rstrip() #remove trailing whitespace
            new = insert(new, ' ',(new.rfind(' ')))
            while (len(new) < n):
                new = insert(new,' ',(new.rfind(' ')))
            printn(new)       

        new = inf.readline(n)


    print '\nclosing files...'
    inf.close()
    print 'input closed'
    of.close()
    print 'output closed'

input:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

If line length n == 37

output:

Lorem ipsum dolor sit amet, consectet
ur adipisicing elit, sed do eiusmod t
magna aliqua. Ut enim ad minim veniam
, quis nostrud exercitation ullamco l
consequat. Duis aute irure dolor in r
cillum dolore eu fugiat nulla pariatu
non proident, sunt in culpa qui offic
ia deserunt mollit anim id est laboru
m                                   .
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T07:35:43+00:00Added an answer on June 4, 2026 at 7:35 am

    I’m having a little trouble understanding what you want to do … It seems like you might want the textwrap module ( http://docs.python.org/library/textwrap.html ). If this isn’t what you want, let me know and I’ll happily delete this answer…

    EDIT

    Does this do what you want?

    s="""Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
    irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
    deserunt mollit anim id est laborum."""
    
    import textwrap
    
    print textwrap.fill(s,37)
    

    EDIT2

    In this situation, I would break your string into substrings that are each N blocks long, store those strings in a list one after another and then I would “\n”.join(list_of_strings) at the end of the day. I won’t code it up though since I suspect this is homework.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I have a reasonable size flat file database of text documents mostly saved in
I have just tried to save a simple *.rtf file with some websites and
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
I would like to run a str_replace or preg_replace which looks for certain words
I need to clean up various Word 'smart' characters in user input, including but
I have a text area in my form which accepts all possible characters from
I am trying to loop through a bunch of documents I have to put

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.