在python中编写计数程序

时间:2012-10-26 05:28:20

标签: python

我是python和编码的新手,我需要帮助解决这个问题。

编写一个将字符串作为输入的程序,并执行以下功能:

▪打印字符串中空格的数量(计数)

▪打印小写字母的数量(计数)

▪打印标点符号数

演示如何在字符串中找到最后一个空格

由于

4 个答案:

答案 0 :(得分:2)

我将向您展示一个示例,为您提供一些想法,让其他人作为练习:

  

打印小写字母的数量(计数)

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

答案 1 :(得分:1)

循环遍历字符串中的字符:

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.punctuationstring.lowercasestring.whitespace。您可以使用the in operator查看该字符是否包含在任何字符集中。

答案 2 :(得分: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
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

注意,在上面,&gt;&gt;&gt;是python解释器的主要提示符,而...是缩进行的辅助提示符。

答案 3 :(得分: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='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'    
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")