2015-04-06 35 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 
相關問題