python 判断字母小写_如何在Python中检测小写字母?

1586010002-jmsa.png

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')

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.

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!

解决方案

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

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']

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'

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值