我是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