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

2024-05-04 22:04:10 发布

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

编写一个程序,生成并打印包含自然数(从1开始)的n个元素(由用户通知n)的列表,并用“ping”替换3的倍数,用“pong”替换7的倍数,用“ping-pong”替换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结尾的数字,我不知道该怎么做。你知道吗


Tags: 用户程序元素密码number列表index结尾
1条回答
网友
1楼 · 发布于 2024-05-04 22:04:10

我试着让你的代码做你想做的,同时尽可能少的修改。你知道吗

  • 不要使用eval。永远不会。坏,坏,坏eval。要将字符串转换为int,请使用int()。你知道吗
  • 你的代码是从0开始的,当它被要求从1开始时,我 改变了范围。你知道吗
  • 为了知道最后一个数字,我根据@Renuka Deshmukh的巧妙注释计算了模10的数字。其他不太聪明的解决方案可能是检查以字符串形式转换的数字的结尾,例如使用str(index).endswith("7")str(index)[-1] == "7"。你知道吗
  • 你想做什么?我删除了==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)

相关问题 更多 >