Basic Python Question on String operations: example: string.lowercase
So I'm trying to run this, but it errors out and I need help understanding what's wrong. I really appreciate any help, I'm taking the MIT opencourseware intro to programming:
words开发者_如何学编程="GreatTimes"
words.lowercase
And I get this error:
AttributeError: 'str' object has no attribute 'lowercase'
The issue is that I'm trying to run example code from "How to think like a computer scientist" and it still gives me the error.
def isLower(ch):
return string.find(string.lowercase, ch) != -1
So I can't figure out what the syntax error is. Looking at the Python doc page it says this:
string.lowercase A string containing all the characters that are considered lowercase letters. On most systems this is the string 'abcdefghijklmnopqrstuvwxyz'. The specific value is locale-dependent, and will be updated when locale.setlocale() is called.
Thoughts?
Edit: Ah, sorry I should be more clear. So I'm trying to write a piece of code that will tell me whether or not a character in a string is lowercase or not. my code is my implementation of it. while the example code is something i'm using to try to check to see if my syntax is wrong and that is the source of the problem. However, the example code also generates an error. In a nutshell, why doesn't this code work? It seems like it Should spit out a string of all the lowercase letters like "reatimes" from "GreatTimes" And/or how would you use string.lowercase to make this program?
I'm a bit confused by what you are trying to do. This seems like a rather contrived exercise.
If you just want to use an instance method,
words.lower()
will return a lowercase version of the stringwords
.If you want to implement a lowercase function of your own using
string.lowercase
(which is just a constant set to a string of all lowercase letters), then you need to make sure you do animport string
before calling it (e.g. in yourlower
function example).If you did an
import string
, you could also usestring.lower('STRING with CAPS')
instead.
Edit: Here's some code that runs your function, to show you it works:
import string
def isLower(ch):
return string.find(string.lowercase, ch) != -1
words = "GreatTimes"
lowercase_letters = ""
for ch in words:
print ch, '->', isLower(ch)
if isLower(ch):
lowercase_letters += ch
print "Lowercase letters were:", lowercase_letters
Output:
G -> False
r -> True
e -> True
a -> True
t -> True
T -> False
i -> True
m -> True
e -> True
s -> True
Lowercase letters were: reatimes
lowercase is the name of a string in the string module:
import string string.lowercase 'abcdefghijklmnopqrstuvwxyz'
but you can't access it through a string instance:
word = 'this is a string' word.lowercase Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'lowercase'
Also, the find method doesn't do what you think -- check the docs.
Allen
Try to use "ascii.lowercase" it works
精彩评论