# -*- 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()
我有点卡在这里:
在我看来,这将是单元测试:字符是否匹配且输出长度是否匹配请求的宽度。