赞成其他两个答案,但只是为了好玩,使用正则表达式:
import re
r = re.compile('.{,20}(?<! )(?= |\Z|\A)')
for s in ('This is a sample text',
'abcdefghijklmnopqrstuvwxyz ',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'This is 1 first sample text ',
'This is 1 again sample text',
'A great blank here',
'Another blank here',
'A short text',
' little indent',
' great indent',
'ocean',
'!',
''):
print ('-----------------------\n'
" ....5...10...15...20\n"
'%r\n%r'
% (s, r.match(s).group() ) )
结果
-----------------------
....5...10...15...20
'This is a sample text'
'This is a sample'
-----------------------
....5...10...15...20
'abcdefghijklmnopqrstuvwxyz '
''
-----------------------
....5...10...15...20
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
''
-----------------------
....5...10...15...20
'This is 1 first sample text '
'This is 1 first'
-----------------------
....5...10...15...20
'This is 1 again sample text'
'This is 1 again'
-----------------------
....5...10...15...20
'A great blank here'
'A great blank'
-----------------------
....5...10...15...20
'Another blank here'
'Another blank'
-----------------------
....5...10...15...20
'A short text'
'A short text'
-----------------------
....5...10...15...20
' little indent'
' little indent'
-----------------------
....5...10...15...20
' great indent'
''
-----------------------
....5...10...15...20
'ocean'
'ocean'
-----------------------
....5...10...15...20
'!'
'!'
-----------------------
....5...10...15...20
''
''