替换字符串中以3和7结尾的数字

时间:2016-10-14 19:07:42

标签: python

编写一个程序,生成并打印一个包含自然数字(从1开始)的n个元素列表(由用户通知),并用“' ping'”的倍数替换3的倍数。 7由“乒乓”字样组成,而3和7的倍数由“乒乓球”字样组成'

以下是

的代码
result = []
number = eval(input("Enter a whole number: "))
for index in range(number):
    if index % 7 == 0 and index % 3 == 0:
        result.append("ping-pong")
    elif index % 3 == 0:
        result.append("ping")
    elif index % 7 == 0:
        result.append("pong")
    else:
        result.append(index)
print(result) == 0

现在还用“PING”这个词替换以3结尾的数字,用“PONG”这个词替换以7结尾的数字,我不知道该如何去做。

1 个答案:

答案 0 :(得分:2)

我尽量让你的代码做你想做的事情,尽可能少做一些修改。

  • 使用eval。永远。坏,坏,坏eval。要将字符串转换为int,请使用int()
  • 你的代码从0开始,当它被要求从1开始时,我 改变了范围。
  • 要知道最后一位数字,我根据@Renuka Deshmukh的聪明评论计算出模数为10的数字。其他不太聪明的解决方案可能是检查作为字符串的数字的结尾,例如str(index).endswith("7")str(index)[-1] == "7"
  • print(result) == 0试图做什么?我删除了==0

以下是生成的代码:

result = []
number = int(input("Enter a whole number: "))
for index in range(1,number+1):
    if index % 7 == 0 and index % 3 == 0:
        result.append("ping-pong")
    elif index % 3 == 0 or index % 10 == 3:
        result.append("ping")
    elif index % 7 == 0 or index % 10 == 7:
        result.append("pong")
    else:
        result.append(index)
print(result)