我想在每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
---------------------------------------------------------------
答案 0 :(得分: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
---------------------------------------------------------------
答案 1 :(得分: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
看起来可以满足您的要求