首页 > 解决方案 > 如何将特定数字替换为单词?

问题描述

如果有输入:

"My phone number is 123780936407, and there are two 0 in it."

我希望输出是:

"My phone number is 123780936407, and there are two zero in it."

但是,如果我使用替换,输出将是:

"My phone number is 12378zero9364zero7, and there are two zero in it."

我该怎么做才能获得理想的输出?非常感谢!

标签: pythonreplace

解决方案


在这种情况下,您可以使用rindex给出特定字符串的最后一个索引。

str1='My phone number is 123780936407, and there are two 0 in it.'
i=str1.rindex('0')

字符串在 Python 中是不可变的,只需创建一个包含所需索引处的值的新字符串。

addStr=' zero '
str1 = str1[:i] + newstring + str1[i + 1:]
print (str1)

推荐阅读