在Python中对齐框架宽度

假设我们有一个单词列表,我们必须逐行将其框在一个矩形区域中。请参阅示例以更好地理解。

因此,如果输入类似于['hello','world','python','programming','nice'],则输出为

***************
* hello       *
* world       *
* python      *
* programming *
* nice        *
***************

为了解决这个问题,我们将遵循以下步骤-

  • l:=数组中最大字的长度

  • st:=放星星(l + 4)次

  • 对于每个我说的话

    • st:= st串联'*'串联我,然后添加大小(i的l-size的空间)串联'*'

  • st:=与st串联星(l + 4)次

  • 返回st

让我们看下面的实现以更好地理解-

示例

class Solution:
   def solve(self, words):
      l=max(len(x) for x in words)
      st='*'*(l+4)+'\n'
      for i in words:
         st+='* '+i+' '*(l-len(i)+1)+'*'+'\n'
      return st+'*'*(l+4)
ob = Solution()words = ['hello','world', 'python', 'programming','nice']
print(ob.solve(words))

输入值

['hello','world', 'python', 'programming','nice']

输出结果

***************
* hello       *
* world       *
* python      *
* programming *
* nice        *
***************