0

If I apply this regex:

re.split(r"(^[^aeiou]+)(?=[aeiouy])", "janu")

on the string "janu", it gives the following result: ['', 'j', 'anu']

Now I want to apply this regex on the following list to get the similar results for each item as above. Can a for loop be used, and if yes, how?

lista = ['janu', 'manu', 'tanu', 'banu']

2 Answers 2

1

You can use a list comprehension:

>>> from re import split
>>> lista = ['janu', 'manu', 'tanu', 'banu']
>>> [split("(^[^aeiou]+)(?=[aeiouy])", x)[1]+"doc" for x in lista]
['jdoc', 'mdoc', 'tdoc', 'bdoc']
>>>

Edit regarding comment:

This will work:

>>> from re import split
>>> lista = ['janu', 'manu', 'tanu', 'banu']
>>> listb = []
>>> for item in lista:
...     data = split("(^[^aeiou]+)(?=[aeiouy])", item)
...     listb.append(data[2]+data[1]+"doc")
...
>>> listb
['anujdoc', 'anumdoc', 'anutdoc', 'anubdoc']
>>>
Sign up to request clarification or add additional context in comments.

8 Comments

Oh my god, there was only a 10 second delay between our two answers.
@randomusername - Yea, that seems to happen alot on SO. 10 secs isn't the best though. I've sometimes posted simultaneously with someone else.
Is there any other way? because it gives nested lists. I have to do an other operation on the list obtained from first item. after completing it, the regexp should move to the second item, and carry on...
lista = ['janu', 'manu', 'tanu', 'banu'] after applying this re.split(r"(^[^aeiou]+)(?=[aeiouy])", lista), the regex shouldn't move to the next item until I concatenate the string at index[2] and the suffix doc. for example: first step: ['', 'j', 'anu'] index[1]+doc = jdoc second step: ['', 'm', 'anu'] index[1]+doc = mdoc Third Step: ['', 't', 'anu'] index[1]+doc = tdoc Fourth step: ['', 'b', 'anu'] index[1]+doc = bdoc ultimately the result should look "jdok mdoc tdok bdoc"
@Coddy - Your end result doesn't match your explanation. Do you want "doc" placed at the end or a back-and-forth of "dok" and "doc"?
|
0

Use the list comprehension

[re.split(r"(^[^aeiou]+)(?=[aeiouy])", i) for i in list]

You can use a for loop but this is considered the pythonic way to do things.

1 Comment

Is there any other way? because it gives nested lists. I have to do an other operation on the list obtained from first item. after completing it, the regexp should move to the second item, and should carry on until the last item in the original list(lista)...

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.