Python中的块字符串而不会破坏单词 [英] chunk string in Python without breaking words

查看:46
本文介绍了Python中的块字符串而不会破坏单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,用于在 20x2 LCD 显示屏上显示一些文本:

#!/usr/bin/pythonLCDCHARS = 20LCDLINES = 2def WriteLCD(text_per_LCD):chunked = (text_per_LCD[i:LCDCHARS+i] for i in range (0, len(text_per_LCD), LCDCHARS))计数_l = 0对于分块的 text_per_line:# 打印将被实际的 LCD 调用替换打印(text_per_line)计数_l += 1如果 count_l >= LCDLINES:# 同意丢失任何额外的行休息WriteLCD("此文本将显示在 %s LCD 行上" % (LCDLINES))

示例字符串将输出

这段文字将显示在 2 条 LCD 线上

我应该怎么做才能在不破坏单词的情况下拆分字符串?即使第二行变得更长并且不再显示,也是如此.

我在 javascript 部分ruby 部分,但我无法将给定的答案翻译成我的 Python 案例.

解决方案

使用 textwrap 模块:

<预><代码>>>>textwrap.wrap("此文本将显示在 3 个 LCD 行上", 20)['此文本将'、'显示在 3 个 LCD'、'行']

I have this code which is meant to display some text on a 20x2 LCD display:

#!/usr/bin/python

LCDCHARS = 20
LCDLINES = 2

def WriteLCD(text_per_LCD):
    chunked = (text_per_LCD[i:LCDCHARS+i] for i in range (0, len(text_per_LCD), LCDCHARS))
    count_l = 0
    for text_per_line in chunked:
        # print will be replaced by actual LCD call
        print (text_per_line)
        count_l += 1
        if count_l >= LCDLINES:
            # agree to lose any extra lines
            break

WriteLCD("This text will display on %s LCD lines" % (LCDLINES))

The example string will output

This text will displ
ay on 2 LCD lines

What should I do to split the string without breaking the words? This even if the second line becomes longer and goes out of display.

I read a similar question on javascript section and another one in ruby section, but I was not able to translate the given answers into my Python case.

解决方案

Use the textwrap module:

>>> textwrap.wrap("This text will display on 3 LCD lines", 20)
['This text will', 'display on 3 LCD', 'lines']

这篇关于Python中的块字符串而不会破坏单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆