Home > Back-end >  Check if the first and the last letter of the string are the same(Python)
Check if the first and the last letter of the string are the same(Python)

Time:12-18

I have a list of strings and I wanted to count how many words are having same first and last letter:


strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]

count = 0 

for word in strings:
   if word[0] == word[-1]:
       count  = 1

print(count)

It gives me a result 0, when its supposed to give 3, what am i doing wrong?

CodePudding user response:

You could use .lower because "a" in not equal to "A".

strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]

count = 0

for word in strings:
    if word[0].lower() == word[-1].lower():
        count  = 1

print(count)

CodePudding user response:

And if you're into list comprehensions, this could also be written as:

sum(word[0].lower() == word[-1].lower() for word in strings)

True and False become 1 and 0 when summed.

  • Related