英文:
Stop words being broken over 2 lines on command line
问题
我正在进行一个项目,该项目会随机选择不超过280个字符的句子,然后使用“打字机效果”将它们打印到命令行。我正在使用树莓派和一个7英寸触摸屏显示器。
在这个论坛和其他地方得到的帮助,我已经让它工作了。我曾经遇到过单词分布在两行的问题,但这里的评论者已经帮助我解决了。然而,我仍然有一个问题,当我使用以下代码:
str2 = textwrap.fill(newTok, 20)
然后将str2与以下代码一起使用:
words = str2 #
for char in words:
sleep(0.1)
sys.stdout.write(char)
sys.stdout.flush()
字符串被分成4行,并占据整整一行。
所以,不是这样:
This is
being split
over four
different lines
而是这样:
This is
being split
over four
different lines.
有任何建议吗?
英文:
I am working on a project that randomly selects sentences of less than 280 characters, and then prints them to the command line using a 'typewriter effect'.I am using a raspberry pi and a 7inch touchscreen monitor.
Thanks to help on this forum and other places I have it working. I had issues with words being split over two lines but commenters here have helped me. However, I am still having one issue, when I use
str2 = textwrap.fill(newTok, 20)
and then use str2 with this
words = str2 #
for char in words:
sleep(0.1)
sys.stdout.write(char)
sys.stdout.flush()
The string is been spaced out over 4 lines and takes up full lines.
so instead of
This is
being split
over four
different lines
It is giving
This is
being split
over four
different lines.
Any suggestions would be great.
答案1
得分: 1
以下是翻译好的部分:
"你似乎想要将字符串换行,但不想在单词中间换行。
你可以使用 textwrap
模块。这将确保你的行在一定数量的字符以下。
import textwrap
str1 = "My long strings need to get wrapped at words, not randomly between characters"
str2 = textwrap.fill(str1, 20)
所以现在如果你 print(str2)
:
My long strings need
to get wrapped at
words, not randomly
between characters
由于你似乎对如何换行感到困惑,这是当你 print(repr(str2))
时会发生的情况:
'My long strings need\nto get wrapped at\nwords, not randomly\nbetween characters'
这些行在 \n
处换行。
要调整已编辑的新问题,其中换行不返回到左边缘的问题,你需要添加回车符 - \r
。
所以 str2 = str2.replace('\n', '\r\n')
。"
英文:
It seems like you want to wrap your strings, just not in the middle of words.
You can use the textwrap
module. This will make sure your lines are under a certain amount of characters.
import textwrap
str1 = "My long strings need to get wrapped at words, not randomly between characters"
str2 = textwrap.fill(str1, 20)
So now if you print(str2)
My long strings need
to get wrapped at
words, not randomly
between characters
Since you seem confused how you line break in general, this is what happens when you print(repr(str2))
'My long strings need\nto get wrapped at\nwords, not randomly\nbetween characters'
The lines break at \n
To adjust for the new problem that has been edited in, where lines breaks do not return to the left margin, you need to add a carriage return - \r
So str2 = str2.replace('\n', \r\n')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论