0

好的,我并没有真正得到我正在寻找的答案,所以我会尝试重新措辞。我需要知道是否有一个函数可以检测字符串中的小写字母。假设我开始编写这个程序:

s = input('Type a word')

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

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

4

2 回答 2

1

Using a regular expression is probably the simplest way:

# Python 3 version

import re

txt = 'MarMaLadE'

# Replace uppercase with "" - an empty string
ltxt,n = re.subn(r'[A-Z]', "", txt) 

print("lower case letters:"," ".join(set(ltxt)))
print("number of lc letters:", n)

The use of set removes duplicate lowercase letters, you might not want that. You might also want to consider which characters are uppercase, is A-Z sufficient? See also the re.LOCALE flag.

于 2012-10-17T03:02:21.000 回答
0

希望这会有所帮助,请记住 python 对缩进很谨慎。这不是一个很好的解决方案,但它有效。

def doWhatYouWantToDo(input):
 newString = ""
 alphabet = "abcdefghijklmnopqrstuvwxyz"
 for letter in input:
  if letter in alphabet:
   newString += letter
 return newString

yourString = 'MarMaLadE'
print doWhatYouWantToDo(yourString)
print len(doWhatYouWantToDo(yourString)
于 2012-10-17T02:49:07.240 回答