Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in python with a remainder? [duplicate]

Tags:

python

split

In python3 I have e.g. the following string

 433 65040    9322 /opt/conda/envs/python2/bin/python -m ipykernel_launcher 

which I want to split in four parts: the first three elements (the numbers) and the remainder as one string. Of course its possible to do it the following way:

text = " 433 65040    9322 /opt/conda/envs/python2/bin/python -m ipykernel_launcher"
pid,rss,etime,*remainder = text.split()
cmd = ' '.join(remainder)

but maybe there is a more pythonic way to do that?

like image 320
Alex Avatar asked Dec 05 '25 07:12

Alex


1 Answers

You can use split with the maxsplit parameter:

text = " 433 65040    9322 /opt/conda/envs/python2/bin/python -m ipykernel_launcher"
text.strip().split(maxsplit=3)  # max 3 splits
# ['433', '65040', '9322', '/opt/conda/envs/python2/bin/python -m ipykernel_launcher']
like image 189
user2390182 Avatar answered Dec 07 '25 20:12

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!