简体   繁体   中英

How can I get the "!" as an item on this split list?

this is my first question!

What should the pattern be in order to make the last "?" appear as an item on this split list?

    import re
    re.split(r'([.?!] )', 'One sentence. Another one? And the last one!')

I get:

['One sentence', '. ', 'Another one', '? ', 'And the last one!']

But I'd like to get this list:

['One sentence', '. ', 'Another one', '? ', 'And the last one', '!']

Thank you!

You can make the space optional (or remove it completely):

import re
re.split(r'([.?!] ?)', 'One sentence. Another one? And the last one!')

Check the demo here .


Or if you really want to ensure the presence of a space, you can allow either the space or the end of string symbol:

import re
re.split(r'[.?!]( |$)', 'One sentence. Another one? And the last one!')

Check the demo here .

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