我是python和編程的新手,我需要幫助解決這個問題。在python中編寫計數程序
編寫一個程序,將一個字符串作爲輸入,並且將執行以下功能:在字符串中
▪打印數量(計數)的空間
▪打印的較低的數目(計數)大寫字母
▪標點符號
的打印數量演示瞭如何找到最後的空間在一個字符串
感謝
我是python和編程的新手,我需要幫助解決這個問題。在python中編寫計數程序
編寫一個程序,將一個字符串作爲輸入,並且將執行以下功能:在字符串中
▪打印數量(計數)的空間
▪打印的較低的數目(計數)大寫字母
▪標點符號
的打印數量演示瞭如何找到最後的空間在一個字符串
感謝
您可以使用filter
和len
來統計事物。例如:
>>> 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解釋器的主要提示符,而...是一個縮進行的第二提示。
我看到和這些string.uppercase等功能已經內置到python中,不需要定義? –
很酷,謝謝。我很感謝你的解釋和你的幫助。 –
遍歷字符串中的字符:
for char in my_string:
# test if char is a space and if it succeeds, increment something
# do the same for your other tests
pass
的string
module有一些常量,可能對您有用;特別是:string.punctuation
,string.lowercase
和string.whitespace
。您可以使用the in
operator來查看角色是否在任何這些字符集中。
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")
你卡在哪裏?如果您提供一些示例代碼並描述您打牆的位置,您將獲得更多幫助。 – RocketDonkey
這聽起來更像是你想要一個你上面列出的東西的工作示例,然後是一個問題,你的「卡住」。 Books,Google,Bing和其他在線資源是您的朋友。如果你來到Stack作爲你的第一個資源,那麼這個問題聽起來像是「爲我做的」,你不會得到任何質量反饋,就會遇到一個實際問題,人們會很樂意提供幫助。這是你希望滑過課程的機會嗎?需要有人爲你做這項工作? – chris