擅长:python、mysql、java
<p>此解决方案不使用<code>re</code>。我修改了你的<code>textDict</code></p>
<pre><code>In [19]: text = "foo 123 doo 342 ghh 568 loo 243"
In [20]: textDict = {"2":"fg" , "3":"gh", "8":"hj"} # modified textDict
In [21]: result_str = ''
In [22]: c_len = 1 # just modify this according to length of dict key
In [23]: for txt in text.split(' '):
...: if txt.isdigit() is True:
...: txt = txt[:-c_len] + textDict.get(txt[-c_len:], txt[-c_len:])
...: result_str += (txt + ' ')
...:
In [24]: result_str.strip() # to remove last space
Out[24]: 'foo 12gh doo 34fg ghh 56hj loo 24gh '
</code></pre>
<p>要回答上一个问题,只需根据dict键长度修改<code>c_len</code>。你知道吗</p>