【问题标题】:how to display matching digits in a string from another number [duplicate]如何显示来自另一个数字的字符串中的匹配数字[重复]
【发布时间】:2020-08-05 07:36:30
【问题描述】:

我是 python 的新手。我正在尝试从给定数字的字符串中找到匹配的数字。我试过以下代码:

st=input("Enter a string")
no=int(input("Enter a number"))
for i in range(len(st)):
while no>0:
rem=no%10
if rem == st[i]:
print(rem)  

【问题讨论】:

  • 缩进在python中非常重要。你的搞砸了 - 也许这是一个剪切和粘贴问题。请修复它以使社区更容易阅读您的代码。这里有一个使用这个网站的提示:告诉我们当你尝试运行你的代码时发生了什么。不要让我们猜测。这只会降低有人花时间帮助您的可能性。
  • 您将字符串与数字进行比较,请使用str(rem) == st[i]rem == int(st[i])

标签: python string loops


【解决方案1】:

这是给你的代码 sn-p:

# Number input
mynumber = input("Enter a number: ")

# Check if input is an integer
try:
    int(mynumber)
except ValueError:
    print("Sorry, not a number")

# String input
mystring = input("Enter a string: ")

# Look for matching numbers in the string and display them
match = ''

for n in mynumber:
    for s in mystring:
        if n == s and not n in match:
            match += n

print('Matching:', match if match else 'None')

【讨论】:

  • 感谢您的回复。我想要数字作为整数数据类型而不是字符串。请你帮我解决这个问题?
  • 您可以使用int(match) 将字符串转换为整数。见python doc
猜你喜欢
  • 2018-10-30
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
相关资源
最近更新 更多