2015-04-06 82 views
-3

所以我是新手编程(和python),如果字符串有零个或一个点字符(“。”字符),并且返回False,如果字符串包含两个或多个点,则必须使该程序返回True使程序返回True如果字符串中有多个点?

这是我现在有的,我不能让它为我工作,请纠正我,如果我错了,谢谢!

def check_dots(text): 
text = [] 

for char in text: 
    if '.' < 2 in text: 
     return True 
    else: 
     return False 
+2

标题说返回False,文本说返回True。 – 2015-04-06 03:02:54

+1

这里有很多错误:(1)在函数开始时不应该将文本设置为空列表。这会导致您搜索'。'的空白列表。 (2)您的代码需要在函数定义行下面缩进。 (3)'如果'。' <2 in text:'不是Python代码的有效行。 – dbliss 2015-04-06 03:03:33

+0

^此评论应该被接受回答。 – Shashank 2015-04-06 03:04:57

回答

1

使用内置Python函数list.count()

if text.count('.') < 2: 
    return True 

它可以是即使代替if-else声明,你做

return text.count('.') < 2 

而且短,也有你的函数的一些错误。所有你需要做的是

def check_dots(text): 
    return text.count('.') < 2 
+0

它会一直返回“无”给我吗?我不明白为什么 – Dom 2015-04-06 03:06:40

+0

@Dom这是因为你正在使用的列表。查看我在回答末尾添加的代码片段 – michaelpri 2015-04-06 03:08:11

+0

非常感谢!我花了这么多时间,这只是一个简单的修复 – Dom 2015-04-06 03:09:32

1

正确的和更短的版本是:

return text.count('.') <= 1 
+0

它为我返回“无”?我很困惑 – Dom 2015-04-06 03:07:34

+0

@Dom检查我们的输入,文本应该是_string_,而不是列表。用'text = []'去掉这一行。 – 2015-04-06 03:10:15

1

Python有一个名为count()

你可以做下面的函数。

if text.count('.') < 2: #it checks for the number of '.' occuring in your string 
    return True 
else: 
    return False 

的快捷方式是:

return text.count('.')<2 

让我们分析一下上面的语句。 在这个部分,text.count('.')<2:它基本上说“我将检查在字符串中出现少于两次的时间段,并根据出现次数返回True或False。”所以如果text.count('。')是3,那么这将是3<2这将成为False

另一个例子。假设一个字符串长度超过7个字符,你希望它返回False

x = input("Enter a string.") 
return len(x)>7 

的代码片段len(x)>7意味着对于的x长度程序检查。让我们假设字符串长度为9.在这种情况下,len(x)将评估为9,那么它将评估为9>7,这是True。

0

我现在要分析你的代码。

def check_dots(text): 
text = [] ################ Don't do this. This makes it a list, 
         # and the thing that you are trying to 
         # do involves strings, not lists. Remove it. 

for char in text: #not needed, delete 
    if '.' < 2 in text: #I see your thinking, but you can use the count() 
         #to do this. so -> if text.count('.')<2: <- That 
         # will do the same thing as you attempted. 
     return True 
    else: 
     return False 
相关问题