Yas*_*mar 3 python string split
输入:
"The boy is running on the train"
Run Code Online (Sandbox Code Playgroud)
预期产量:
["The boy", "boy is", "is running", "running on", "on the", "the train"]
Run Code Online (Sandbox Code Playgroud)
在python中实现这一目标的最简单方法是什么?
line="The boy is running on the train"
words=line.split()
k=[words[index]+' '+words[index+1] for index in xrange(len(words)-1)]
print k
Run Code Online (Sandbox Code Playgroud)
产量
['The boy', 'boy is', 'is running', 'running on', 'on the', 'the train']
Run Code Online (Sandbox Code Playgroud)
你拆分所有空格,然后重新加入对:
words = inputstr.split()
secondwords = iter(words)
next(secondwords)
output = [' '.join((first, second))
for first, second in zip(words, secondwords)]
Run Code Online (Sandbox Code Playgroud)
演示:
>>> inputstr = "The boy is running on the train"
>>> words = inputstr.split()
>>> secondwords = iter(words)
>>> next(secondwords) # output is ignored
'The'
>>> [' '.join((first, second)) for first, second in zip(words, secondwords)]
['The boy', 'boy is', 'is running', 'running on', 'on the', 'the train']
Run Code Online (Sandbox Code Playgroud)