3

我想在每 20 个字符后加上 \n ....

My_string = "aaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffff"

我试过这个:a = "\n".join(re.findall("(?s).{,20}", My_string))[0:-1]

每当我打印时:

print '''
              ---------------------------------------------------------------
               Value of a is 
            %s
              ---------------------------------------------------------------
        ''' % a

输出:

     ---------------------------------------------------------------
                          Value of a is
                          aaaaaaaaaaaaaaaaaaab
bbbbbbbbbbbbbbbbbbbc
cccccccccccccccccccd
ddddddddddddddddddde
eeeeeeeeeeeeeeeeeeef
fffffffffffffffffff
                          ---------------------------------------------------------------

我想要像这样的输出:

           ---------------------------------------------------------------
           Value of a is 
           aaaaaaaaaaaaaaaaaaab
           bbbbbbbbbbbbbbbbbbbc
           cccccccccccccccccccd
           ddddddddddddddddddde
           eeeeeeeeeeeeeeeeeeef
           fffffffffffffffffff
           ---------------------------------------------------------------
4

2 回答 2

2

您想要创建所有行的列表,包括预定义的和包装的,然后在每行前面添加空格标识(最好在一个步骤中以避免重复代码),然后将所有内容连接到一个字符串中。

虽然正则表达式可以解决问题,但请看一个不错的标准模块textwrap,它允许您换行:

import textwrap

My_string = "aaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffff"


print '\n'.join('              {0}'.format(line) for line in [
                '---------------------------------------------------------------',
                'Value of a is'] + textwrap.fill(My_string, 20).split('\n') +
                ['---------------------------------------------------------------'])

印刷

              ---------------------------------------------------------------
              Value of a is
              aaaaaaaaaaaaaaaaaaab
              bbbbbbbbbbbbbbbbbbbc
              cccccccccccccccccccd
              ddddddddddddddddddde
              eeeeeeeeeeeeeeeeeeef
              fffffffffffffffffff
              ---------------------------------------------------------------
于 2013-02-21T07:37:09.803 回答
0

试试这个:

# -*- encoding: utf-8 -*-
import re

My_string = "aaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffff"
split="\n     "
a = split.join(re.findall("(?s).{,20}", My_string))[0:-1]



print '''     ---------------------------------------------------------------
     Value of a is 
     %s ---------------------------------------------------------------''' % a

看起来可以满足你的要求

于 2013-02-21T08:06:37.163 回答