Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to partial split and take the first portion of string in Python?

Have a scenario where I wanted to split a string partially and pick up the 1st portion of the string.

  1. Say String could be like aloha_maui_d0_b0 or new_york_d9_b10. Note: After d its numerical and it could be any size.

  2. I wanted to partially strip any string before _d* i.e. wanted only _d0_b0 or _d9_b10.

  3. Tried below code, but obviously it removes the split term as well.

    print(("aloha_maui_d0_b0").split("_d"))
    #Output is : ['aloha_maui', '0_b0']
    #But Wanted : _d0_b0
    
  4. Is there any other way to get the partial portion? Do I need to try out in regexp?

like image 824
Vimo Avatar asked Dec 06 '25 06:12

Vimo


2 Answers

How about just

stArr = "aloha_maui_d0_b0".split("_d")
st2 = '_d' + stArr[1]

This should do the trick if the string always has a '_d' in it

like image 103
Rob T Avatar answered Dec 07 '25 20:12

Rob T


You can use index() to split in 2 parts:

s = 'aloha_maui_d0_b0'
idx = s.index('_d')
l = [s[:idx], s[idx:]]
# l = ['aloha_maui', '_d0_b0']

Edit: You can also use this if you have multiple _d in your string:

s = 'aloha_maui_d0_b0_d1_b1_d2_b2'
idxs = [n for n in range(len(s)) if n == 0 or s.find('_d', n) == n]
parts = [s[i:j] for i,j in zip(idxs, idxs[1:]+[None])]
# parts = ['aloha_maui', '_d0_b0', '_d1_b1', '_d2_b2']
like image 30
thibsc Avatar answered Dec 07 '25 20:12

thibsc