在字符串上循环两次:



好的,所以我写这段代码是为了识别889范围内的8。每次运行这段代码时,我都会得到值241,这是错误的。for循环迭代该值,当它找到8时,它会附加该值。但是,他们的数字是881888它不向前看并附加第二个或第三个8。我该如何解决这个问题或再次重申

temp = [] # Contains number with 8 in it.
for i in range(0, 889):
if '8' in str(i):
r_temp.append(i)

print(temp)
values = [] # Takes in the 8 in the integer
i = '8'
for z in r_temp:
if i in str(z):
values.append(i)

您需要使用list-comprehension:计算str中出现8的时间

print(sum([str(x).count('8') for x in range(0,889)]))

text.count('pattern'(方法可以在这里使用:

total_count = 0
# loop from 0 ... 889
for number in range(0, 889):
# convert the integer to a string
number_as_string = str(number)
# get the number of '8' in the string
count_of_8_in_str = number_as_string.count('8')
# sum up 
total_count = total_count + count_of_8_in_str
print(total_count)

最新更新