Home > Software engineering >  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?

Time:03-15

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??

CodePudding user response:

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.

CodePudding user response:

You are matching only a single * character in your regex, you need to match all just like you do with \w by adding . Is there any reason behind needing an answer without modules?

CodePudding user response:

You can use a regex like (\* ) with re.split.


import re
test='asdf****adec****awd**wer*'

a=test.strip()
s=list(filter(None, re.split(r'([*] )', a)))
print(s)

Will ouput:

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

Which you can try online in this demo


Using filter to remove the empty string in the list

  • Related