Вы можете адаптировать следующий образец для удовлетворения ваших требований:
Если цифры для замены находятся только в конце слов:
import re
s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'(?<=[a-zA-Z])\d+$', '$', w) for w in x]
print(y)
Выход:
['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b', '123']
В один шаг (результат в виде строки):
import re
s ="Question1: a12 is the number of a, 1b is the number of b, abc1uvf"
pat = re.compile(r'(?<=[a-zA-Z])\d+(?=\W)')
print(re.sub(pat, "$", s))
Выход:
Question$: a$ is the number of a, 1b is the number of b, abc1uvf
Если числа могут быть расположены в любом месте слова:
import re
s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'\d+', '$', w) for w in x]
print(y)
Выход:
['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '$']
Обратите внимание, что 123
заменяется на $
, если это не то, что вы хотите использовать:
import re
s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', '$', w) for w in x]
print(y)
Выход:
['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '123']
За один шаг:
import re
s = "Question1: a12 is the number of a, 1b is the number of b, 123"
y = re.sub(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', '$', s)
print(y)