将长字符串换成换行符的好方法吗?
在我的项目中,我有一堆从文件中读取的字符串。当在命令控制台中打印时,其中大多数字符的长度超过80个字符并环绕,看起来很丑。
我希望能够让Python读取该字符串,然后测试其长度是否超过75个字符。如果是这样,则将字符串分成多个字符串,然后在新行上一个接一个地打印。我也希望它很聪明,而不是断断续续。即"The
quick brown <newline> fox..."
代替"the quick bro<newline>wn fox..."
。
我试过修改类似的代码,该代码会在设置长度后将字符串截断,但只是将字符串丢弃而不是将其放在新行中。
我可以使用哪些方法来完成此任务?
-
您可以使用
textwrap
模块:>>> import textwrap >>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly." >>> print(textwrap.fill(strs, 20)) In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly.
帮助
上textwrap.fill
:>>> textwrap.fill? Definition: textwrap.fill(text, width=70, **kwargs) Docstring: Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour.
使用
regex
,如果你不想合并一行到另一行:import re strs = """In my project, I have a bunch of strings that are. Read in from a file. Most of them, when printed in the command console, exceed 80. Characters in length and wrap around, looking ugly.""" print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs))) # Reading a single line at once: for x in strs.splitlines(): print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))
输出:
In my project, I have a bunch of strings that are. Read in from a file. Most of them, when printed in the command console, exceed 80. Characters in length and wrap around, looking ugly.