[英]Check if the first and the last letter of the string are the same(Python)
我有一個字符串列表,我想計算有多少單詞的首字母和尾字母相同:
strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]
count = 0
for word in strings:
if word[0] == word[-1]:
count += 1
print(count)
它給了我一個結果 0,當它應該給 3 時,我做錯了什么?
您可以使用.lower
,因為“a”不等於“A”。
strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]
count = 0
for word in strings:
if word[0].lower() == word[-1].lower():
count += 1
print(count)
如果你喜歡列表理解,這也可以寫成:
sum(word[0].lower() == word[-1].lower() for word in strings)
True
和False
求和時變為 1 和 0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.