简体   繁体   中英

split text into lines by the number of characters

I have some text for example:

'This is a line of text over 10 characters'

That I need to be broken into lines consisting of no more than 10 characters without breaking words unless I need to (for example a line with work containing more than 10 characters).

The line above would turn into:

'This is a\nline of\ntext over\n10\ncharacters'

It's a fairly simple problem but I'd like to hear how people would do it. I'm going to start coding it and post my solution in a little while as well.

You need textwrap

>>> import textwrap
>>> s = 'This is a line of text over 10 characters'
>>> textwrap.fill(s, width=10)
'This is a\nline of\ntext over\n10\ncharacters'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM