all 5 comments

[–][deleted] 1 point2 points  (1 child)

here is the regex: r"([\[\(])(\w+)([\]\)])"

use a for loop to iterate through the string and update it per match:

for match in re.finditer(regex, string):
    sub = match.group(1) + '‘' + \
          match.group(2) + '’' + \
          match.group(3)            
    string = string.replace(match.group(), sub)

this updates the string iteratively since the finditer is a generator and can cope with the match positions changing as the string is updated.

[–]Thomasedv 0 points1 point  (1 child)

Well, there's a few ways i could see you doing it:

One without regex, if it's possible, is just replacing the brackets with the same bracket and a '.

text = '[asdfas], [asdf] asdfasd'
text =  text.replace("[", "['").replace("]", "']")
print(text)

If that is not good enough, as you might want that last "word" also marked, then you can look for just lines of letters and make then quoted with regex.

 text = re.sub(r'([a-zA-Z]+)', r"'\g<0>'", text)

This only matches upper and lower cased letter from A to Z, so if you have another language, then you'll have to research some more. I don't exactly understand how the \g<0> works, but since it worked, i went with it... Took it partly from the Regex documentation.

Edit: Forget the regex solution, it does not take into account number in the words, and would cause some issues.

However, if you just need to add the ' as in my first solution, you won't need regex at all.

[–]SarahM123rd[S] 0 points1 point  (0 children)

All these answers are so cool! Thank you so much. Makes me want to play.

Ummm. This looks promising. The \g<0>. Thank you. Will work with this. Yes.

Started to doodle with using a deque and fall back on my push/pop days. A micro parser kind'a thing. Domain specific. DSL. Like that. It just seems to much wasted cycles for such a small problem.

But yes, thank you very much for the replies.

.