找出数字在一个数中出现的次数
我现在遇到了一些问题,我不知道怎么用for循环来找出一个数字中某个数字出现了多少次。如果有人有一些简单的想法,我是新手,对Python还不太了解。
#Assignment 6
#Start out with print instructions
print """
This program will take a Number and Digit that you enter.
It will then find the number of times the digit is in your number.
Afterwards, this program will multiply your number by your digit.
"""
#Get the user's number
number = raw_input("Enter a number: ")
#Use a while loop to make sure the number is valid
while (number == ""):
print "You have entered an invalid number."
number = raw_input("Enter another number: ")
#Get the digit
digit = raw_input("Enter a digit between 0-9: ")
#Use a while loop to make sure the digit is valid
while (int(digit) > 9):
print "You have entered an invalid digit."
digit = raw_input("Enter a digit between 0-9: ")
#Set the count to 0
count = 0
#Show the user their number and digit
print "Your number is:", number, "And your digit is:", digit
#Use the for loop to determine how many times the digit is in the number
for d in number:
if d == digit
count +=1
else
count +=0
print d, count
3 个回答
1
你可以把用户输入的内容当作字符串来处理,然后像这样逐个查看字符串中的字符:
number = "12423543534543"
digit = "3"
你可能想把其中的一些代码放到一个方法里,而不是直接写在这里。
count = 0
for d in number:
if d == digit:
count += 1
print matched
5
在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们需要将它们转换成程序可以使用的格式。
比如说,如果你从一个网页上获取了一些信息,这些信息可能是以文本的形式存在的。为了让程序能够使用这些信息,我们可能需要将它们转换成数字、日期或者其他类型的数据。这种转换的过程就叫做“数据解析”。
在解析数据时,我们通常会使用一些特定的规则或者格式,比如JSON、XML等。这些格式就像是数据的“语言”,让不同的程序能够相互理解。
总之,数据解析就是把复杂的数据变得简单易懂的过程,这样程序才能顺利地处理和使用这些数据。
>>> '123123123123111'.count('3')
4
2
你的代码在目前的状态下是语法错误的,
if d == digit
count +=1
else
count +=0
缺少冒号:
if d == digit:
count +=1
else:
count +=0 # or just pass, or better, skip the whole else tree
除此之外,代码是可以运行的,不过你应该处理一下当第一个(或者第二个)输入是,比如说,a
时可能出现的错误。
你还没有解决这个子任务:
之后,这个程序会把你的数字和你的数字相乘。
Python教程会对你了解如何进行数字相乘非常有帮助。