From ['The', 'range', 'of', 'number', 'is', 'to']
to ['The range of number is', 'to']
How to combine the first 5th strings into one string while keeping the 6th one alone?
With len()
and split()
method.
CodePudding user response:
Well, not exactly with those methods, since you don't need them.
>>> x = ['The', 'range', 'of', 'number', 'is', 'to']
>>> [" ".join(x[:-1])] [x[-1]]
['The range of number is', 'to']
The idea is to join all strings but the last with a space, then append the last word as a list.
Another option would be to use join
and rsplit
, which is arguably easier to read:
>>> " ".join(x).rsplit(" ", 1)
['The range of number is', 'to']
CodePudding user response:
you can do this:
>>> var = ['The', 'range', 'of', 'number', 'is', 'to']
>>> [" ".join(var[:5]), " ".join(var[5:])]
['The range of number is', 'to']