Write a program that reads in and justifies a line of text to fit a column width of 40. Justification is achieved bv: finding the gaps between words increasing the gaps to have more spaces some gaps may require one more space than some of the other gaps When your program is running, the display should look like this: Enter a line of text: Hello there! How are you today? 1234567890123456789012345678901234567890 Hello there! HOW are you today?
时间: 2023-12-14 18:38:57 浏览: 88
Here's a Python program that does what you've described:
```python
def justify(text, width):
words = text.split()
num_words = len(words)
num_gaps = num_words - 1
total_spaces = width - len(text)
if num_gaps == 0:
return text.center(width)
else:
avg_spaces = total_spaces // num_gaps
extra_spaces = total_spaces % num_gaps
justified_text = words[0]
for i in range(1, num_words):
num_spaces = avg_spaces
if i <= extra_spaces:
num_spaces += 1
justified_text += ' ' * num_spaces + words[i]
return justified_text
text = input("Enter a line of text: ")
justified_text = justify(text, 40)
print(justified_text)
```
You can run this program in a Python environment (e.g. IDLE or Jupyter Notebook) and enter a line of text when prompted. The program will then justify the text to fit a column width of 40 and print the resulting text.
阅读全文