python读取字符串中的单词_python – 在字符串切片中包含完整的单词

这是我的一些代码:

def breakUp(x,chunk_size):

return [ x[i:i+chunk_size] for i in range(0, len(x), chunk_size) ]

这是它的工作原理:

In [8]: breakUp('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!',10)

Out[8]:

['This is a ',

'cool sente',

'nce... How',

' about eat',

'ing it??? ',

'Whats more',

'?? pepper ',

'is availab',

'le all for',

' free!!!']

但正如你在第二个元素中所看到的那样,单词句子并没有完全被采用,它说“sente”……

我知道这是因为我已经要求python将其拆分为每10个字符…无论如何指定我想在每10个字符之后拆分但是如果是第10个字符.一言以蔽之,全拿一字……?

解决方法:

电池包括:

>>> import textwrap

>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15)

This is a cool

sentence... How

about eating

it??? Whats

more?? pepper

is available

all for free!!!

这几乎就是你所要求的.除非你指定10作为第二个参数,它仍然会拆分句子……因为没有办法让它适合10个字符.但是,如果要执行此操作,可以使用break_long_words = False自定义textwrap:

>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 10, break_long_words=False)

This is a

cool

sentence...

How about

eating

it???

Whats

more??

pepper is

available

all for

free!!!

标签:python,loops,string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值