我有一个由各种长度的子字符串组成的字符串,这些子字符串之间用空格分隔。我想在空格处将该字符串分成多行,但前提是每个子字符串的长度都超过给定的数量(例如,如果给定单词的长度超过8个字符,则在此之前和之后添加新行;如果出现空格与上一个新行相距少于9个字符,请保持原样。
例:
input_text = 'string made up of some incredibly long words and some short words'
如果不检查子字符串的长度,我只能执行一个简单的regex命令
print(re.sub(' ','\n', input_text))
但这只会应用一个哑巴替代品,并且您可能会连续使用1或2个字符的多行。
我不知道如何检查子字符串的长度,并根据该标准智能地替换/离开。
所需的输出:
string
made up
of some
incredibly
long
words and
some
short
words
谢谢!
试试换行
import textwrap
input_text = 'string made up of some incredibly long words and some short words'
print('\n'.join(textwrap.wrap(input_text, 9, break_long_words=False)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句