2012-10-26 29 views
-5

我是python和編程的新手,我需要幫助解決這個問題。在python中編寫計數程序

編寫一個程序,將一個字符串作爲輸入,並且將執行以下功能:在字符串中

▪打印數量(計數)的空間

▪打印的較低的數目(計數)大寫字母

▪標點符號

的打印數量演示瞭如何找到最後的空間在一個字符串

感謝

+11

你卡在哪裏?如果您提供一些示例代碼並描述您打牆的位置,您將獲得更多幫助。 – RocketDonkey

+0

這聽起來更像是你想要一個你上面列出的東西的工作示例,然後是一個問題,你的「卡住」。 Books,Google,Bing和其他在線資源是您的朋友。如果你來到Stack作爲你的第一個資源,那麼這個問題聽起來像是「爲我做的」,你不會得到任何質量反饋,就會遇到一個實際問題,人們會很樂意提供幫助。這是你希望滑過課程的機會嗎?需要有人爲你做這項工作? – chris

回答

0

您可以使用filterlen來統計事物。例如:

>>> import string 
>>> s="This char -- or that one -- It's a Space." 
>>> for k in [string.uppercase, string.lowercase, string.whitespace, string.punctuation]: 
...  len(filter(lambda x: x in k, s)) 
... 
3 
23 
9 
6 

注意,string.uppercase, string.lowercase,等值在string模塊中定義,並導入string模塊後,即可使用。它們中的每一個都是一個字符串值;例如:

>>> string.whitespace 
'\t\n\x0b\x0c\r ' 
>>> string.punctuation 
'!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~' 

注意,在上面,>>>是python解釋器的主要提示符,而...是一個縮進行的第二提示。

+0

我看到和這些string.uppercase等功能已經內置到python中,不需要定義? –

+0

很酷,謝謝。我很感謝你的解釋和你的幫助。 –

2

我會告訴你一個例子給一些想法供你玩周圍,並保留其他鍛鍊:小寫字母

打印數量(計數)

>>> my_str = "Hello world!!" 
>>> sum(1 for x in my_str if x.islower()) 
9 
+0

這個例子有幫助,謝謝。 –

+0

你也可以在my_str中寫'sum(x.islower()for x)' – Blender

+0

這是正確的,但是我個人發現bool是int的一個子類,在python中是一個醜陋的皺紋,我不喜歡依靠它。 – wim

0
a=input("type strint :") 
space=" " 
print(a.count(space)) 
lower=0 
for w in a: 
    if w.islower()==True: 
     lower+=1 
print(lower) 
punc='!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~'  
pmark=0 
for p in a: 
    if p in punc: 
     pmark+=1 
print(pmark) 

# Demonstrate how you would find the last space in a string 
if a[-1]== space: 
    print("last space yes")