Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list and rejoin it using the same separator

Tags:

python

string

Take the following string:

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

If I were to split it using:

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

I would get:

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

Then, to each element of the new list I would run a function, say:

y = map(str.upper, x)

How could I rejoin it using the original separators? In the above example, the rejoining process would result with:

"HELLO,WORLD,HOW-ARE-YOU?H"
like image 341
Beta Decay Avatar asked Sep 27 '22 09:09

Beta Decay


1 Answers

Use re.sub instead:

import re
def change(m):
  return str.upper(m.group(0))
x = re.sub("[a-zA-Z]", change, string)
like image 158
hjpotter92 Avatar answered Sep 30 '22 08:09

hjpotter92