使用python将字符串拆分定义的长度

时间:2016-01-07 11:18:30

标签: python

假设我有一个字符串..

lyrics = "Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you"

我只想在一行显示23个字符:

Never gonna give you up
Never gonna let you dow
n Never gonna run aroun
d and desert you Never 
gonna make you cry Neve
r gonna say goodbye Nev
er gonna tell a lie and
hurt you

(希望我没有搞砸了,让我们假装每行有24个字符,我很困,我甚至无法计算)

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

通过re.findall功能。

>>> import re
>>> lyrics = "Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you"
>>> for i in re.findall(r'.{1,23}', lyrics):
    print i


Never gonna give you up
 Never gonna let you do
wn Never gonna run arou
nd and desert you Never
 gonna make you cry Nev
er gonna say goodbye Ne
ver gonna tell a lie an
d hurt you