问题
I want to make sure that I only print maximum 80 character long lines, but I have a string s
that can be both shorter and longer than that. So I want to split it into lines without splitting any words.
Example of long string:
s = "This is a long string that is holding more than 80 characters and thus should be split into several lines. That is if everything is working properly and nicely and all that. No mishaps no typos. No bugs. But I want the code too look good too. That's the problem!"
I can devise ways of doing this such as:
words = s.split(" ")
line = ""
for w in words:
if len(line) + len(w) <= 80:
line += "%s " % w
else:
print line
line ="%s " % w
print line
Equally I could use s.find(" ")
iteratively in a while-loop:
sub_str_left = 0
pos = 0
next_pos = s.find(" ", pos)
while next_pos > -1:
if next_pos - sub_str_left > 80:
print s[sub_str_left:pos-sub_str_left]
sub_str_left = pos + 1
pos = next_pos
next_pos = s.find(" ", pos)
print s[sub_str_left:]
None of these are very elegant, so my question is if there's a cooler pythonic way of doing this? (Maybe with regex or so.)
回答1:
There's a module for that: textwrap
For instance, you can use
print '\n'.join(textwrap.wrap(s, 80))
or
print textwrap.fill(s, 80)
回答2:
import re
re.findall('.{1,80}(?:\W|$)', s)
回答3:
import re
s = "This is a long string that is holding more than 80 characters and thus should be split into several lines. That is if everything is working properly and nicely and all that. No misshaps no typos. No bugs. But I want the code too look good too. That's the problem!"
print '\n'.join(line.strip() for line in re.findall(r'.{1,80}(?:\s+|$)', s))
output:
This is a long string that is holding more than 80 characters and thus should be
split into several lines. That is if everything is working properly and nicely
and all that. No misshaps no typos. No bugs. But I want the code too look good
too. That's the problem!
回答4:
You can try this python script
import os, sys, re
s = "This is a long string that is holding more than 80 characters and thus should be split into several lines. That is if everything is working properly and nicely and all that. No misshaps no typos. No bugs. But I want the code too look good too. That's the problem!"
limit = 83
n = int(len(s)/limit)
b = 0
j= 0
for i in range(n+2):
while 1:
if s[limit - j] not in [" ","\t"]:
j = j+1
else:
limit = limit - j
break
st = s[b:i*limit]
print st
b = i*limit
来源:https://stackoverflow.com/questions/9968173/is-there-a-nice-way-splitting-a-potentially-long-string-without-splitting-in-w