1

I have strings which contains certain words with the following form:

'something1__something2__need'

for example here is a full string with those words:

'bla__wewe__23,sad__fd__sas po__oop__retq2'

I want to extract a new string with only the last sub-word in each word in the string, meaning that my first example turns into 'need' and the second into '23,sas retq2'. Possible delimiters are spaces and commas. Should be without loops if possible.

3
  • You need to specify exactly what a word-boundary and a "sub-word" boundary are in your case. Then you can easily solve this via a regular expression. Commented Sep 17, 2018 at 10:35
  • @TommyF words are everything between commas and spaces and sub-words are the words between '__'. Commented Sep 17, 2018 at 10:36
  • Single Regex solution: _([^_,]+)([,\s]|\Z) your result is in the first capture group. Paste it here with your testdata to get an explanation: regex101.com Commented Sep 17, 2018 at 10:46

1 Answer 1

1

Using Regex.

Demo:

import re

s = ['something1__something2__need', 'bla__wewe__23,sad__fd__sas po__oop__retq2']
for i in s:
    val = re.split(r"([,\s])", i)     #Split by space, comma
    print("".join(j.split("__")[-1] for j in val))    #Split by __ and join by last element in list.

Output:

need
23,sas retq2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.