【发布时间】:2021-11-30 06:45:34
【问题描述】:
给出一个没有开头和结尾空格的字符串。有必要改变它,使字符串的长度变得等于指定的长度,大于字符串的当前长度。这应该通过在单词之间插入额外的空格来完成。单个单词之间的空格数不应相差超过一个空格(即,空格平均添加)。
字符串本身由用户从键盘输入。老师说我需要用切片来解决问题,但我不明白具体怎么做。问题是事先不知道输入的字符串有多长。以及其中会有多少初始差距。同时,最后一行的长度必须与用户输入的长度完全一致。
这是我到目前为止的想法。如果最初没有空格,则此代码会在输入行的开头和结尾均匀地添加空格。
line_0 = input('Enter the required line:\n')
print('Current string length:\n', len(line_0), sep = '')
num_0 = len(line_0)
num_1 = int(input('Enter the total length of the string:\n'))
num_d = num_1 - num_0
s = line_0.count(' ')
line_1 = ''
if s == 0:
if (num_d % 2) != 0:
cup_1 = ' ' * (num_d // 2 + 1)
cup_2 = ' ' * (num_d // 2)
line_1 = cup_1 + line_0 + cup_2
else:
cup_1 = ' ' * (num_d // 2)
line_1 = cup_1 + line_0 + cup_1
print("'^' - the beginning and end of the line (not included in the
length of the final line).")
print('The resulting string is long ', len(line_1), ':\n', '^', line_1,
'^', sep = '')
【问题讨论】:
标签: python python-3.x task