I am trying to calculate every lowercase letter from a mixed uppercase and lowercase string and form a new string of only lowercase. For example I have a string named st="ABcASFatBD" and I expect an output of low= "cat" but I am getting only "c" as the output. Below is my code.
class Solution(object):
def find_crowd(self, st):
lo = ""
for i in range(len(st)):
if st[i].islower():
lo = st[i]
return lo
else:
pass
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBD"
print(p.find_crowd(s))
CodePudding user response:
The problem is that you have your script ending on the first time it finds a lowercase value, whereas your return lo
should be outside of the for i in range(...):
. But heres a simpler version of your code:
class Solution(object):
def find_crowd(self, st):
lo = ""
lo = ''.join([char for char in st if char.islower() == True])
return lo
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBD"
print(p.find_crowd(s))
Hope this helps
CodePudding user response:
The problem with your code is that you call return statement in your if statement which ends the loop
without passing through the end of your string.
class Solution(object):
def find_crowd(self, st):
lo = ""
for i in range(len(st)):
if st[i].islower():
lo = st[i]
return lo
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBD"
print(p.find_crowd(s))
You can also convert your string into a list of characters before iterating on it and getting an individual element. You can convert a string into a list using [*s]
. Just see the output of the print below to understand. Here is the simplest way to do that:
class Solution(object):
def find_crowd(self, st):
lo = ""
for i in [*st]:
if i.islower():
lo = i
return lo
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBD"
print([*s])
print(p.find_crowd(s))
CodePudding user response:
Your function is returning when first lowercase character is obtained.!
Some solutions are:-
class Solution(object):
def find_crowd(self, st):
lo=""
for i in range(len(st)):
if st[i].islower():
lo = st[i]
return lo
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBD"
print(p.find_crowd(s))
Using ord() function [Ascii Values]:-
class Solution(object):
def find_crowd(self, st):
lo=""
for i in st:
if ord(i)>=97 and ord(i)<=122:
lo = i
return lo
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBDZzaA"
print(p.find_crowd(s))
One liner [Pythonic Way]:-
class Solution(object):
def find_crowd(self, st):
return "".join([lower for lower in st if lower.islower() == True])
if __name__ == "__main__":
p = Solution()
s = "ABcASFatBDZzaA"
print(p.find_crowd(s))