samedi 4 juin 2016

How to find find a grouping of upper and lower case characters in a string in python 3

I'm working on Python Challenges, and the level I'm on asks us to find a lower case letter surrounded on both sides by exactly three upper case letters. I've written the following code, which seems pretty crude but I feel should work. However, all I get is an empty string.

source="Hello there" #the string I have to work with key=""#where I want to put the characters that fit for i in source: if i==i.lower(): # if it's uppercase x=source.index(i) #makes number that's the index of i if source[x-1].upper()==source[x-1] and source[x-2]==source[x-2].upper() and source[x-3].upper()==source[x-3]: #checks that the three numbers before it are upper case if source[x+1].upper()==source[x+1] and source[x+2].upper()==source[x+2] and source[x+3].upper()==source[x+3]: #checks three numbers after are uppercase if source[x+4].lower()==source[x=4] and source[x-4].lower()==source[x-4]: #checks that the fourth numbers are lowercase key+=i #adds the character to key print(key):

I know this is really, really messy but I don't understand why it just returns an empty string. If you have any idea what's wrong, or a more efficient way to do it, I would really appreciate it. Thanks

Aucun commentaire:

Enregistrer un commentaire