简体   繁体   中英

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:

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

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM