在循环中缩进多行对象的行

时间:2017-08-06 20:52:35

标签: python loops format

我试图缩进以下输出

Thresh
Communication is key when making use of Thresh's lantern.
Let your teammates know how you like to use it.
Death Sentence and Flay can be combined in either cast order for powerful 
combinations.
Thresh can collect souls without needing to kill units himself.
Planning your map position to be near the most deaths will help to maximize 
soul collection.

我希望它缩进看起来如下:

 Thresh
  Communication is key when making use of Thresh's lantern.
  Let your teammates know how you like to use it.
  Death Sentence and Flay can be combined in either cast order for powerful 
  combinations.
  Thresh can collect souls without needing to kill units himself.
  Planning your map position to be near the most deaths will help to 
  maximize soul collection.

我使用它作为我的代码我可以为每个发生的sting实例分配值,但这通常会发生变化,为每个场景执行if和try语句(例如有3个提示)将是困难和不切实际的2个提示然后3个提示和3个敌人提示

        try:
            for i in range(0,len(self.j['data'][champEntry]['allytips'])):
                self.allyTips0 += self.j['data'][champEntry]['allytips'][i].replace('.', '.\n').replace('!', '!\n').replace("\n ", "\n")
            self.allyTips0 = self.allyTips0
            self.allyTips0 = '```\n{0}\n{1}```'.format(champEntry, self.allyTips0)

        except Exception as e:
            raise e

1 个答案:

答案 0 :(得分:2)

textwrap库旨在帮助解决此问题。这个样本应该产生上面显示的结果作为样本输出...

import textwrap

a = '''Thresh
Communication is key when making use of Thresh's lantern.
Let your teammates know how you like to use it.
Death Sentence and Flay can be combined in either cast order for powerful
combinations.
Thresh can collect souls without needing to kill units himself.
Planning your map position to be near the most deaths will help to maximize
soul collection.'''

wrapper = textwrap.TextWrapper(initial_indent=" ", subsequent_indent="    ")

for line in wrapper.wrap(a):
    print(line)

有关详细信息,请参阅textwrap library的文档: