-->

如何检测在Python小写字母?(How to detect lowercase letters i

2019-06-18 12:53发布

我需要知道是否有检测字符串中的小写字母的功能。 说我开始写这个程序:

s = input('Type a word')

会不会有一个功能,让我发现字符串s中的小写字母? 也许结束了分配这些字母在不同的变量,或只是打印小写字母或小写字母数。

虽然这些是我想它,我最感兴趣的是如何检测的小写字母存在做什么。 最简单的方法将受到欢迎,我只是在介绍Python的过程,所以我的老师不希望看到复杂的解决方案时,我把我的期中考试。 谢谢您的帮助!

Answer 1:

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

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

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


也许结束了分配这些字母在不同的变量。

要做到这一点,我建议使用列表理解,虽然你可能没有你的课程涵盖这个尚未:

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

或者让你可以使用一个字符串''.join与发电机:

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


Answer 2:

您可以使用内置函数any和发电机。

>>> any(c.islower() for c in 'Word')
True

>>> any(c.islower() for c in 'WORD')
False


Answer 3:

有两种不同的方式,你可以找小写字符:

  1. 使用str.islower()找到小写字符。 与列表理解相结合,你可以收集所有小写字母:

     lowercase = [c for c in s if c.islower()] 
  2. 你可以使用正则表达式:

     import re lc = re.compile('[az]+') lowercase = lc.findall(s) 

第一个方法返回单个字符的列表,所述第二返回字符的列表:

>>> import re
>>> lc = re.compile('[a-z]+')
>>> lc.findall('AbcDeif')
['bc', 'eif']


Answer 4:

有许多方法,这里有一些:

  1. 使用预定义函数character.islower():

     >>> c = 'a' >>> print(c.islower()) #this prints True 
  2. 使用ord()函数来检查信的ASCII码是否处于小写字符的ASCII码的范围:

     >>> c = 'a' >>> print(ord(c) in range(97,123)) #this will print True 
  3. 检查是否信等于它的小写:

     >>> c = 'a' >>> print(c.lower()==c) #this will print True 

但事实可能并非是所有的,你可以找到你自己的方式,如果你不喜欢这些的:D。

最后,让我们开始检测:

d = str(input('enter a string : '))
lowers = [c for c in d if c.islower()]
#here i used islower() because it's the shortest and most-reliable one (being a predefined function), using this list comprehension is the most efficient way of doing this


Answer 5:

您应该使用raw_input获得一个字符串输入。 然后使用islower的方法str对象。

s = raw_input('Type a word')
l = []
for c in s.strip():
    if c.islower():
        print c
        l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)

做就是了 -

dir(s)

你会发现islower和其他属性str



Answer 6:

import re
s = raw_input('Type a word: ')
slower=''.join(re.findall(r'[a-z]',s))
supper=''.join(re.findall(r'[A-Z]',s))
print slower, supper

打印:

Type a word: A Title of a Book
itleofaook ATB

或者你可以使用一个列表理解/发电机表达式:

slower=''.join(c for c in s if c.islower())
supper=''.join(c for c in s if c.isupper())
print slower, supper

打印:

Type a word: A Title of a Book
itleofaook ATB


文章来源: How to detect lowercase letters in Python?