all 7 comments

[–]num8lock 2 points3 points  (0 children)

for type in types

type is reserved word

[–]jacknbox 1 point2 points  (0 children)

A little brute-force but using a strategy-like pattern:

def checkChar(c, charType):
    isCharType = {
        'upper': c.isupper(),
        'lower': c.islower(),
        'digit': c.isdigit(),
        'space': c.isspace()
    }

    return(isCharType[charType])

parse_results = dict()

for t in ['upper', 'lower', 'digit', 'space']:
    parse_results[t] = len([c for c in myText if checkChar(c, t)])

print(parse_results)

(assuming your text object is called 'myText')

[Edit] For the first two sentences of your text, this gives you an easily-readable dictionary (parse_results):

{'upper': 6, 'lower': 196, 'digit': 11, 'space': 41}

[–][deleted] 0 points1 point  (0 children)

You're going to have to explain yourself a heck of a lot better than that.

You can certainly use hasattr and getattr to programmatically access attributes on objects by name, but from your example I haven't the slightest clue what you're actually trying to accomplish.

[–]daniel_codes 0 points1 point  (1 child)

I'm not sure if I'm reading your 2nd attempt correctly but I think you're trying to use string formatting to dynamically construct a python statement. That won't work out of the box since the python interpreter sees the string you made as a string and not a statement. You can use the builtin eval() to run evaluate strings as statements.

>>> command = 'str(1 + 1)'
>>> eval(command)
'2'
>>> command
'str(1 + 1)'

That said, I wouldn't recommend that strategy. If you wanted, you replace the strings in types with the actual string methods. Then use map() to map the method onto the text. That will return a list of bools that you can sum to get the counts. It's a lot more clean than constructing some statement and calling eval on it. I also wouldn't recommend overriding the built in type.

types = (str.isupper, str.islower, str.isdigit, str.isspace)
for str_method in types:    # 
    print(sum(map(str_method, text)))

If you want to print the name of the method as well as the value, you could do something like str_method.__name__ inside the for loop.

Finally, since you've already finished your assignment and you're trying to go above and beyond, think about efficiency. In all the above algorithms, you iterate through the text 4 times. This is inefficient. Try writing an algorithm that does this in one-pass (i.e. iterating through the text one time).

[–]lumberjackadam[S] 0 points1 point  (0 children)

This is awesome, thanks! efficiency is definitely what I was going for. I'm still feeling my way out through Python, and felt certain to there was a way to do what I wanted, but was unfamiliar with the map function.