Python 如何找到某个数字所在的每个数字

Python 如何找到某个数字所在的每个数字,python,Python,我想知道如何列出包含某个数字的所有数字(来自输入),我该怎么做 我已经试过查看StackOverflow,并尝试了一些来自answers的代码,但没有成功,我相信我做错了什么,请帮助 我的代码: a = int(input("Search for: ")) b = int(input("In range up to: ")) numbers = range(0, b) expected_numbers = [i for i in numbers if a in str(i)] print(exp

我想知道如何列出包含某个数字的所有数字(来自输入),我该怎么做

我已经试过查看StackOverflow,并尝试了一些来自answers的代码,但没有成功,我相信我做错了什么,请帮助

我的代码:

a = int(input("Search for: "))
b = int(input("In range up to: "))
numbers = range(0, b)
expected_numbers = [i for i in numbers if a in str(i)]
print(expected_numbers)
这是我收到的错误消息:

Traceback (most recent call last):
  File "program.py", line 4, in <module>
    expected_numbers=[i for i in numbers if a in str(i)]
  File "program.py", line 4, in <listcomp>
    expected_numbers=[i for i in numbers if a in str(i)]
TypeError: 'in <string>' requires string as left operand, not int
回溯(最近一次呼叫最后一次):
文件“program.py”,第4行,在
预期的_数=[i为i,如果str中有a(i)]
文件“program.py”,第4行,在
预期的_数=[i为i,如果str中有a(i)]
TypeError:“in”需要字符串作为左操作数,而不是int
谢谢你的帮助。

这里

a = input()
b = int(input())
expected_numbers = [i for i in range(b) if a in str(i)]
print(expected_numbers)
实际上你把“a”作为整数。休息,一切都是正确的

如果要打印它,而不只是修改最后一行

for i in expected_numbers:
    print(i,"contains",a)

您将获得所需的结果。

只是一个小错误,请将变量
a
转换为
str

`expected_numbers = [i for i in range(b) if str(a) in str(i)]`

另请注意:使用此选项了解StackOverflow上的格式选项。:)

您的优化版本无法正常工作。只需尝试
a=13
b=2000
,您将得到不包含
13
的结果。数字是一个范围在(0-9)之间的单个值。你所说的情况。。这是一个数字。在问题中提到了数字字。Fair anough,我的坏,但是然后考虑案例<代码> a=1,b=20 < /C> >,您仍然错过了解决方案中的所有数字<代码> 12, 13, 14,…,19 < /代码>。是的。现在明白了。我将尝试查看这些案例,并用正确的答案再次发布。谢谢。谢谢,但我也试着像这样打印输出:搜索范围为:12的:2 2包含2 12包含2有什么想法吗?