【问题标题】:Pad a Python string to a specified length将 Python 字符串填充到指定长度
【发布时间】: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


    【解决方案1】:

    首先,您需要计算需要添加多少个空格。 同时,您将在单词列表中拆分初始字符串。 然后,您计算要添加到每个单词的最小空格量,以及您将添加到前 n 个单词的剩余空格。 最后,您添加空格并将单词和空格最大化。

    initial_sentence = "Lorem ipsum dolor sit amet"
    spaces_to_add = int(input("Length needed : ")) - len(initial_sentence)
    words = initial_sentence.split(" ")
    number_words = len(words) - 1
    
    min_spaces_added = spaces_to_add // number_words
    spaces_remaining = spaces_to_add % number_words
    
    final_string = ""
    
    for word_ID in range(number_words) :
       final_string = final_string + words[word_ID] + " "*(1+min_spaces_added) #the initial space after the word that has been removed by the .split() + the minimum required
       if word_ID+1 <= spaces_remaining :
          final_string += " "
    final_string += words[-1]#the last word
    print(final_string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2016-01-31
      • 2013-12-17
      • 1970-01-01
      • 2020-03-04
      • 2014-05-22
      相关资源
      最近更新 更多