我如何用字符串替换 15。我正在尝试用字符串 "go" 替换列表中可被 15 整除的任何数字?

  • 本文关键字:替换 字符串 任何 数字 何用 go 列表 python
  • 更新时间 :
  • 英文 :

def b_function(low, high):
g = []
for i in range(low,high):
if i % 3 ==0 or i % 7 ==0 or i % 15 ==0:
#print(str(g) +" ",end = " ")
g.insert(len(g),i)
#i.replace("15","boo")
#if i % 15 ==0:
#g.append("Boo")
print(g)
if __name__ == "__main__":
num_1 = int(input("Please input the lower limit:n"))
num_2 = int(input("Please input the upper limit:n"))
c = b_function(num_1,num_2)

我让用户输入范围,以及我将如何用字符串"0"替换所有可被15整除的数字;去";。

修改列表的一个简单方法是使用创建另一个列表的理解:

>>> numbers = [5, 10, 15, 20, 25, 30, 35, 40, 45]
>>> [n if n % 15 else "go" for n in numbers]
[5, 10, 'go', 20, 25, 'go', 35, 40, 'go']

您运行过代码吗?它会引发错误,可能无法像您预期的那样工作。

# there are more conditions than number divisible by 15, 
# the if statement execute for the first condition that is True,
# in this case, all number divisible by 3
if i % 3 ==0 or i % 7 ==0 or i % 15 ==0:
# so you will have a list of numbers divisible by 3, even if it is a list of numbers
# divisible by 15, and you successfully replace, you only get a list full of "go"
# as there are no other numbers inserted under if statement
g.insert(len(g),i)
# raise AttributeError here because integer input doesn't have replace function, 
# even it works, you only replace 15 not 30 or 45 etc. and the word will be "boo"
i.replace("15","boo")
# your print function is in the for-loop, so if there are 6 numbers divisible by 15,
# the list will be printed 6 times, is that what you want?
print(g)

请注意,在范围(a,b(中,b是排他性的,例如,范围(0100(的数字从0到99,不包括100。

你可能想要这样的东西吗?

def b_function(low, high):
g = []
# high+1 to include the num_2
for i in range(low,high+1):
# directly append "go" to the list when the number is divisible by 15
# so no need to replace
if i % 15 == 0:
g.append("go")
# regular print out for numbers divisible by 3 or 7
elif i % 3 == 0 or i % 7 ==0:
g.append(i)
# only print the list once after the for-loop
print(g)
if __name__ == "__main__":
num_1 = int(input("Please input the lower limit:n"))
num_2 = int(input("Please input the upper limit:n"))
c = b_function(num_1,num_2)

输出为:

[3, 6, 7, 9, 12, 14, 'go', 18, 21, 24, 27, 28, 'go']

最新更新