数字的python搜索字符串,在它们周围放置括号

Eld*_*mir 0 python regex numbers insert

我正在尝试在字符串中搜索数字,并在找到它们时,在它们周围包裹一些字符,例如

a = "hello, i am 8 years old and have 12 toys"
a = method(a)
print a
"hello, i am \ref{8} years old and have \ref{12} toys"
Run Code Online (Sandbox Code Playgroud)

我看过re(正则表达式)库,但似乎找不到任何有用的东西......任何很酷的想法?

Mar*_*ers 5

这是该.sub方法的基本用法:

numbers = re.compile(r'(\d+)')

a = numbers.sub(r'\ref{\1}', a)
Run Code Online (Sandbox Code Playgroud)

\d+数字模式周围的画面创建一个组,并且该\1引用将替换为该组的内容.

>>> import re
>>> a = "hello, i am 8 years old and have 12 toys"
>>> numbers = re.compile(r'(\d+)')
>>> a = numbers.sub(r'\\ref{\1}', a)
>>> print a
hello, i am \ref{8} years old and have \ref{12} toys
Run Code Online (Sandbox Code Playgroud)