2012-10-26 61 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")