如何将特定数字替换为单词?

2024-04-26 07:06:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如果有输入:

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

我希望输出是:

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

但是,如果使用replace,输出将是:

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

我怎样才能得到理想的输出?非常感谢!你知道吗


Tags: andinnumberismyphoneitare
1条回答
网友
1楼 · 发布于 2024-04-26 07:06:08

在本例中,可以使用rindex,它给出特定字符串的最后一个索引。你知道吗

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

字符串是immutable在Python中,只需创建一个新字符串,其中包含所需索引处的值。你知道吗

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

相关问题 更多 >