本文介绍了如何在Python中检测小写字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道是否有一个检测字符串中小写字母的函数.假设我开始编写此程序:

I need to know if there is a function that detects the lowercase letters in a string. Say I started writing this program:

s = input('Type a word')

是否有一个函数可以让我检测字符串s中的小写字母?可能最终将这些字母分配给其他变量,或者仅打印小写字母或小写字母的数量.

Would there be a function that lets me detect a lowercase letter within the string s? Possibly ending up with assigning those letters to a different variable, or just printing the lowercase letters or number of lowercase letters.

虽然这些是我想使用的,但我最感兴趣的是如何检测小写字母的存在.欢迎使用最简单的方法,因为我只是在python入门课程中,所以我的老师在上学期中时不想看到复杂的解决方案.感谢您的帮助!

While those would be what I would like to do with it I'm most interested in how to detect the presence of lowercase letters. The simplest methods would be welcome, I am only in an introductory python course so my teacher wouldn't want to see complex solutions when I take my midterm. Thanks for the help!

推荐答案

要检查字符是否为小写,请使用strislower方法.这个简单的命令式程序会打印字符串中的所有小写字母:

To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:

for c in s:
    if c.islower():
         print c

请注意,在Python 3中,应使用print(c)而不是print c.

Note that in Python 3 you should use print(c) instead of print c.

要做到这一点,我建议您使用列表理解功能,尽管您在课程中可能还没有涵盖以下内容:

To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:

>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']

或者要获取字符串,可以将''.join与生成器一起使用:

Or to get a string you can use ''.join with a generator:

>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'

这篇关于如何在Python中检测小写字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:20