Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Insert numbers in string between quotes

Tags:

python

regex

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?

like image 639
Hyperion Avatar asked Jan 04 '23 12:01

Hyperion


2 Answers

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.

like image 124
ash Avatar answered Jan 12 '23 00:01

ash


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"'
like image 24
farsil Avatar answered Jan 11 '23 23:01

farsil