How to split the string if special character in string and keep the string in same python?
For Example:
Input:
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.