How can I get a full justification of text in python












0















# -*- coding: utf-8 -*-
import io


def main():
global get_user_input
global stringInput
global width
stringInput = ''
width = ''
get_user_input = input("Please enter a string to Justify and the width to justify at using a | to separate the string and width: " )

def left_justify(stringInput, width) :
#single line only
return ' '.join(stringInput).ljust(width)

def justify(stringInput, width) :
output = io.StringIO()
justifyInput = stringInput.split(' ')
line = # List of words in current line.
col = 0 # Starting column of next word added to line.

for word in justifyInput:
if line and col + len(word) > width:
if len(line) == 1:
output.write(left_justify(line, width))
else:
# After n + 1 spaces are placed between each pair of words,
#there are spaces left over; these result in wider spaces at the left.
n, r = divmod(width - col + 1, len(line) - 1)
narrow = ' ' * (n + 1)
if r == 0:
output.write(narrow.join(line))
else:
wide = ' ' * (n + 2)
output.write(wide.join(line[:r] + [narrow.join(line[r:])]))
line, col = , 0
line.append(word)
col += len(word) + 1
if line:
output.write(left_justify(line, width))
return output.getvalue()

def print_the_output():
print(justify(stringInput, width))

main()

if "|" not in get_user_input :
print("please ensure you used a | to separate the string from the jusfitication width")
elif get_user_input.find('|') != -1:
try:
stringInput = get_user_input.split('|')[0].strip('|').lstrip(' ')
val = str(stringInput)
print("nthe following string will be processed for justification: %s" %stringInput.strip('|'))
except ValueError:
print("please ensure the string to justify is text")
try:
width = int(get_user_input.split('|')[1].strip('|'))
val = int(width)
print("nThe justification will occur at a width of: %s" %width)
except ValueError:
print("nplease ensure your justification width is an integer")
else:
print(' ')
print_the_output()


I am a little bit stuck here:




  1. when there is only 1 line for the string I am not sure if it is using the entire width specified; thus making the string justified across the entire width.

  2. to verify that #1 is happening I need to find a way to show the position for each character in the string and thus proving it used the entire width amount. (so if there are 10 characters it would so 01234567890 counting everything, spaces included)

  3. from #2 I would want to figure out a way to record the incoming string character at index say 8 and store it and check if that character matches the output and check the total length matches width.


In my head those would be the unit tests: do the characters match and does the output length match the requested width.










share|improve this question



























    0















    # -*- coding: utf-8 -*-
    import io


    def main():
    global get_user_input
    global stringInput
    global width
    stringInput = ''
    width = ''
    get_user_input = input("Please enter a string to Justify and the width to justify at using a | to separate the string and width: " )

    def left_justify(stringInput, width) :
    #single line only
    return ' '.join(stringInput).ljust(width)

    def justify(stringInput, width) :
    output = io.StringIO()
    justifyInput = stringInput.split(' ')
    line = # List of words in current line.
    col = 0 # Starting column of next word added to line.

    for word in justifyInput:
    if line and col + len(word) > width:
    if len(line) == 1:
    output.write(left_justify(line, width))
    else:
    # After n + 1 spaces are placed between each pair of words,
    #there are spaces left over; these result in wider spaces at the left.
    n, r = divmod(width - col + 1, len(line) - 1)
    narrow = ' ' * (n + 1)
    if r == 0:
    output.write(narrow.join(line))
    else:
    wide = ' ' * (n + 2)
    output.write(wide.join(line[:r] + [narrow.join(line[r:])]))
    line, col = , 0
    line.append(word)
    col += len(word) + 1
    if line:
    output.write(left_justify(line, width))
    return output.getvalue()

    def print_the_output():
    print(justify(stringInput, width))

    main()

    if "|" not in get_user_input :
    print("please ensure you used a | to separate the string from the jusfitication width")
    elif get_user_input.find('|') != -1:
    try:
    stringInput = get_user_input.split('|')[0].strip('|').lstrip(' ')
    val = str(stringInput)
    print("nthe following string will be processed for justification: %s" %stringInput.strip('|'))
    except ValueError:
    print("please ensure the string to justify is text")
    try:
    width = int(get_user_input.split('|')[1].strip('|'))
    val = int(width)
    print("nThe justification will occur at a width of: %s" %width)
    except ValueError:
    print("nplease ensure your justification width is an integer")
    else:
    print(' ')
    print_the_output()


    I am a little bit stuck here:




    1. when there is only 1 line for the string I am not sure if it is using the entire width specified; thus making the string justified across the entire width.

    2. to verify that #1 is happening I need to find a way to show the position for each character in the string and thus proving it used the entire width amount. (so if there are 10 characters it would so 01234567890 counting everything, spaces included)

    3. from #2 I would want to figure out a way to record the incoming string character at index say 8 and store it and check if that character matches the output and check the total length matches width.


    In my head those would be the unit tests: do the characters match and does the output length match the requested width.










    share|improve this question

























      0












      0








      0








      # -*- coding: utf-8 -*-
      import io


      def main():
      global get_user_input
      global stringInput
      global width
      stringInput = ''
      width = ''
      get_user_input = input("Please enter a string to Justify and the width to justify at using a | to separate the string and width: " )

      def left_justify(stringInput, width) :
      #single line only
      return ' '.join(stringInput).ljust(width)

      def justify(stringInput, width) :
      output = io.StringIO()
      justifyInput = stringInput.split(' ')
      line = # List of words in current line.
      col = 0 # Starting column of next word added to line.

      for word in justifyInput:
      if line and col + len(word) > width:
      if len(line) == 1:
      output.write(left_justify(line, width))
      else:
      # After n + 1 spaces are placed between each pair of words,
      #there are spaces left over; these result in wider spaces at the left.
      n, r = divmod(width - col + 1, len(line) - 1)
      narrow = ' ' * (n + 1)
      if r == 0:
      output.write(narrow.join(line))
      else:
      wide = ' ' * (n + 2)
      output.write(wide.join(line[:r] + [narrow.join(line[r:])]))
      line, col = , 0
      line.append(word)
      col += len(word) + 1
      if line:
      output.write(left_justify(line, width))
      return output.getvalue()

      def print_the_output():
      print(justify(stringInput, width))

      main()

      if "|" not in get_user_input :
      print("please ensure you used a | to separate the string from the jusfitication width")
      elif get_user_input.find('|') != -1:
      try:
      stringInput = get_user_input.split('|')[0].strip('|').lstrip(' ')
      val = str(stringInput)
      print("nthe following string will be processed for justification: %s" %stringInput.strip('|'))
      except ValueError:
      print("please ensure the string to justify is text")
      try:
      width = int(get_user_input.split('|')[1].strip('|'))
      val = int(width)
      print("nThe justification will occur at a width of: %s" %width)
      except ValueError:
      print("nplease ensure your justification width is an integer")
      else:
      print(' ')
      print_the_output()


      I am a little bit stuck here:




      1. when there is only 1 line for the string I am not sure if it is using the entire width specified; thus making the string justified across the entire width.

      2. to verify that #1 is happening I need to find a way to show the position for each character in the string and thus proving it used the entire width amount. (so if there are 10 characters it would so 01234567890 counting everything, spaces included)

      3. from #2 I would want to figure out a way to record the incoming string character at index say 8 and store it and check if that character matches the output and check the total length matches width.


      In my head those would be the unit tests: do the characters match and does the output length match the requested width.










      share|improve this question














      # -*- coding: utf-8 -*-
      import io


      def main():
      global get_user_input
      global stringInput
      global width
      stringInput = ''
      width = ''
      get_user_input = input("Please enter a string to Justify and the width to justify at using a | to separate the string and width: " )

      def left_justify(stringInput, width) :
      #single line only
      return ' '.join(stringInput).ljust(width)

      def justify(stringInput, width) :
      output = io.StringIO()
      justifyInput = stringInput.split(' ')
      line = # List of words in current line.
      col = 0 # Starting column of next word added to line.

      for word in justifyInput:
      if line and col + len(word) > width:
      if len(line) == 1:
      output.write(left_justify(line, width))
      else:
      # After n + 1 spaces are placed between each pair of words,
      #there are spaces left over; these result in wider spaces at the left.
      n, r = divmod(width - col + 1, len(line) - 1)
      narrow = ' ' * (n + 1)
      if r == 0:
      output.write(narrow.join(line))
      else:
      wide = ' ' * (n + 2)
      output.write(wide.join(line[:r] + [narrow.join(line[r:])]))
      line, col = , 0
      line.append(word)
      col += len(word) + 1
      if line:
      output.write(left_justify(line, width))
      return output.getvalue()

      def print_the_output():
      print(justify(stringInput, width))

      main()

      if "|" not in get_user_input :
      print("please ensure you used a | to separate the string from the jusfitication width")
      elif get_user_input.find('|') != -1:
      try:
      stringInput = get_user_input.split('|')[0].strip('|').lstrip(' ')
      val = str(stringInput)
      print("nthe following string will be processed for justification: %s" %stringInput.strip('|'))
      except ValueError:
      print("please ensure the string to justify is text")
      try:
      width = int(get_user_input.split('|')[1].strip('|'))
      val = int(width)
      print("nThe justification will occur at a width of: %s" %width)
      except ValueError:
      print("nplease ensure your justification width is an integer")
      else:
      print(' ')
      print_the_output()


      I am a little bit stuck here:




      1. when there is only 1 line for the string I am not sure if it is using the entire width specified; thus making the string justified across the entire width.

      2. to verify that #1 is happening I need to find a way to show the position for each character in the string and thus proving it used the entire width amount. (so if there are 10 characters it would so 01234567890 counting everything, spaces included)

      3. from #2 I would want to figure out a way to record the incoming string character at index say 8 and store it and check if that character matches the output and check the total length matches width.


      In my head those would be the unit tests: do the characters match and does the output length match the requested width.







      python-3.x






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 1:25









      ShenanigatorShenanigator

      18916




      18916
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454402%2fhow-can-i-get-a-full-justification-of-text-in-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454402%2fhow-can-i-get-a-full-justification-of-text-in-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Contact image not getting when fetch all contact list from iPhone by CNContact

          count number of partitions of a set with n elements into k subsets

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks