2

I have a string : 'testing: ' and want to replace it with ' "testing:" '. In other words, add quotations around the word inside the string

I've tried using

re.sub('[a-zA-Z]+:', '"${name}"',word)

but this just replaces it with {name}

pault
  • 41,343
  • 15
  • 107
  • 149

2 Answers2

2

Your original expression is just fine, we'd just add a capturing group around it,

([A-Za-z]+:)

Demo

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([A-Za-z]+:)"

test_str = "testing:"

subst = "\"\\1\""

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Output

"testing:"

Examples of re.sub

result = re.sub(pattern, repl, string, count=0, flags=0);

result = re.sub('abc',  '',    input)           # Delete pattern abc
result = re.sub('abc',  'def', input)           # Replace pattern abc -> def
result = re.sub(r'\s+', ' ',   input)           # Eliminate duplicate whitespaces
result = re.sub('abc(def)ghi', r'\1', input)    # Replace a string with a part of itself

Reference

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
2

You may use \g<0> backreference to refer to the whole match:

The backreference \g<0> substitutes in the entire substring matched by the RE.

Code:

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

See the Python demo

import re
word = 'testing:  '
word = re.sub(r'[a-zA-Z]+:', r'"\g<0>"',word)
print(word) # => "testing:"  
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563