Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split the string if special character in string and keep the string in same python?

How to split the string if special character in string and keep the string in same python?

For Example:

Input:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

asdf****adec****awd**wer*

Needed Output:

['asdf','****','adec','****','awd','**','wer','*']

My code:

import re
a=input().strip()
s=re.findall('[*]|\w+', a)
print(s)

My output:

['asdf', '*', '*', '*', '*', 'adec', '*', '*', '*', '*', 'awd', '*', '*', 'wer', '*']

What mistake i made?? my special characters are printind seperately .

Is there any method without using modules??

>Solution :

For me your task is better served by re.split rather than re.findall, consider that

import re
text = "asdf****adec****awd**wer*"
parts = re.split(r'(\*+)',text)
print(parts)

output

['asdf', '****', 'adec', '****', 'awd', '**', 'wer', '*', '']

Note that I used captured group to inform re.split to keep separators and also there is empty string in parts and it is considered part after last separators, if this is not acceptable then do

parts = [p for p in re.split(r'(\*+)',text) if p]

Note: I used so-called raw-string to make escaping easier, as * has special meaning if you want literal * you must espace it or put in [ and ]. See re docs for discussion of using raw-strings for re needs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading