Split the list and attach it using the same separator

Take the following line:

"Hello,world,how-are you?h" 

If I split it using:

 import re x = re.split("[^a-zA-Z]", string) 

I would get:

 ["Hello","world","how","are","you","h"] 

Then, for each item in the new list, I will run a function, say:

 y = map(str.upper, x) 

How can I connect to it using the original delimiters? In the above example, the reunion process will result in:

 "HELLO,WORLD,HOW-ARE-YOU?H" 
+5
source share
1 answer

Use re.sub instead:

 import re def change(m): return str.upper(m.group(0)) x = re.sub("[a-zA-Z]", change, string) 
+4
source

Source: https://habr.com/ru/post/1234588/


All Articles