有人能给我指出正确的方向吗。。你知道吗
我有一个包含单词句子的字符串 e、 g.“他试图学习一种pythonic,或者regex,解决问题的方法”
这个字符串非常大,我需要把它分成多行,每行不能超过64个字符。 但我不能每64个字符插入一个换行符。我需要确保换行符出现在第64个字符之前最接近的字符(来自一组字符)处,以确保行不超过64个字符。 e、 我只能在空格、逗号或句号后插入换行符
我还需要解决方案是相当有效的,因为这是一个行动,将发生很多次。你知道吗
我不确定textwrap是否是解决问题的方法,因为我需要保留输入字符串中的原始换行符。 示例:
long_str = """
123456789 123456789 123456789 123456789 123456789 123456789
Line 1: Artificial intelligence (AI), sometimes called machine intelligence,
Line 2: is intelligence demonstrated by machines,
Line 3: in contrast to the natural intelligence displayed by humans and other animals.
Line 4: In computer science AI research is defined as
"""
lines = textwrap.wrap(long_str, 60, break_long_words=False)
print('\n'.join(lines))
我想要的是:
123456789 123456789 123456789 123456789 123456789 123456789 Line 1: Artificial intelligence (AI), sometimes called machine intelligence, Line 2: is intelligence demonstrated by machines, Line 3: in contrast to the natural intelligence displayed by humans and other animals. Line 4: In computer science AI research is defined as
但是textwrap给了我这个:
123456789 123456789 123456789 123456789 123456789 123456789 Line 1: Artificial intelligence (AI), sometimes called machine intelligence, Line 2: is intelligence demonstrated by machines, Line 3: in contrast to the natural intelligence displayed by humans and other animals. Line 4: In computer science AI research is defined as
我怀疑Regex可能是答案,但我在试图用Regex解决这个问题时已经超出了我的深度。你知道吗
在换行符上将长字符串拆分为单独的行。“像往常一样”包装每一行,然后将所有内容再次连接到一个字符串中。你知道吗
由于
textwrap
返回一个字符串列表,您不需要做任何其他事情,只需要继续将它们粘贴在一起,并在末尾连接它们。你知道吗如果您能提供您已经尝试过的任何代码,它可能会帮助我们回答您的问题。也就是说,我相信下面的示例代码将保留现有的换行符,将超过64个字符的行换行,并保留字符串其余部分的格式。你知道吗
Python的输出是:
每this
相关问题 更多 >
编程相关推荐