如何在Python中检测小写字母?

编程入门 行业动态 更新时间:2024-10-27 20:35:28
本文介绍了如何在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!

推荐答案

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

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.

可能最终将这些字母分配给另一个变量.

Possibly ending up with assigning those letters to a different variable.

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

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中检测小写字母?

本文发布于:2023-10-16 17:05:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498196.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字母   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!