【问题标题】:Python string grouping?Python字符串分组?
【发布时间】:2015-05-20 15:07:17
【问题描述】:
基本上,我打印一条长消息,但我想将所有这些单词组合成 5 个字符长的字符串。
例如 “iPhone 6 不仅仅是更大——它在各方面都更好。更大,但明显更薄。”我想做到这一点
“iPhon 6 isn' tsimp lybig ger-it'sbe terri never yway. Large r, but Drama tical lythi nner。”
【问题讨论】:
标签:
python
grouping
chunks
【解决方案1】:
正如@vaultah 所建议的,这是通过将字符串用空格分隔并在没有空格的情况下将它们连接回来来实现的;然后使用 for 循环将切片操作的结果附加到数组中。一个优雅的解决方案是使用推导式。
text = "iPhone 6 不仅仅是更大——它在各方面都更好。更大,但明显更薄。"
加入文本 = ''.join(text.split())
splitted_to_six = [joined_text[char:char+6] for char in range(0,len(joined_text),6)]
' '.join(splitted_to_six)
我相信您可以使用 re 模块来恢复破折号和撇号,因为它们本来应该是
【解决方案2】:
只需执行以下操作。
import re
sentence="iPhone 6 isn't simply bigger - it's better in every way. Larger, yet dramatically thinner."
sentence = re.sub(' ', '', sentence)
count=0
new_sentence=''
for i in sentence:
if(count%5==0 and count!=0):
new_sentence=new_sentence+' '
new_sentence=new_sentence+i
count=count+1
打印新句子
输出:
iPhon e6isn 'tsim plybi gger- it'sb etter ineve ryway .Larg er,ye tdram atica llyth inner .