如何在python中使用余数拆分字符串?

时间:2018-09-20 11:51:32

标签: python split

在python3中,我有以下字符串

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

我想分为四个部分:前三个元素(数字),其余作为一个字符串。当然可以通过以下方式做到这一点:

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

但是也许有更多的pythonic方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以将splitmaxsplit参数一起使用:

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']