I need to replace every number in a string with the number itself but between quotes:
str = 'This is number 1 and this is number 22'
Result:
str= 'This is number "1" and this is number "22"'
I know I can use use this regex to replace every number in a string with another string:
str = re.sub("\d", "x", str)
but this would give me:
str= 'This is number x and this is number xx'
How to replace with the matched number itself modified?
You can use the \1
construct to refer to matched groups.
>>> re.sub(r"(\d+)", r'"\1"', "This is number 1 and this is number 22")
'This is number "1" and this is number "22"'
Note the use of raw strings (prefixed with r) to avoid having to escape the backslash – you should be using a raw string for the pattern to match as well, otherwise the \d
may be interpreted as an escape in the future.
In addition, the pattern (\d+)
matches any number of digits in a row, rather than just one digit – without this, a string like This is number "1" and this is number "2""2"
would be produced.
You don't even need regular expressions for something this simple:
>>> words = 'This is number 1 and this is number 22'
>>> " ".join('"{}"'.format(x) if x.isdigit() else x for x in words.split())
'This is number "1" and this is number "22"'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With