例如:“两个鳟鱼吃吐司”将返回数字2(鳟鱼,吐司)
到目前为止,这是我的代码。做这个程序的最好方法是什么?
string = input("Enter a string ")
words = string.split()
number = 0
if (word[0].lower() == word[len(word)-1].lower()):
number += 1
print(number)
答案 0 :(得分:4)
您非常接近所需的内容。您需要遍历words
来测试每个单词:
string = input("Enter a string: ")
words = string.split()
number = 0
# iterate over `words` to test each word.
for word in words:
# word[len(word)-1] can be replaced with just word[-1].
if (word[0].lower() == word[-1].lower()):
number += 1
print(number)
使用给定的示例运行上述程序会产生结果:
Enter a string: Two trout eat toast
2
执行上述操作的一种更干净的方法可能是在迭代输入字符串并使用sum
之前将输入字符串小写:
words = input("Enter a string: ").lower().split()
number = sum(word[0] == word[-1] for word in words)
print(number) # 2
答案 1 :(得分:2)
如果您想要单线:
print(sum([1 for word in input("Enter a string").lower().split() if word[0] == word[-1]]))
答案 2 :(得分:0)
b = a.split()
c = 0
for item in b:
if item[0] == item[-1]:
c+=1
print(c)
答案 3 :(得分:0)
如果您想要一个简单的细分...
s = 'i love you Dad'
l =[]
l = s.split(' ')
count = 0
for i in l:
if len(i)==1:
print(i)
else:
if i[0].upper()==i[len(i)-1].upper():
count = count+1
print(i)
print(count)
Output: i
Dad
1
答案 4 :(得分:0)
您在这里
example = "Two trout eat toast"
example = (example.lower()).split()
count = 0
for i in example:
i = list(i)
if i[0] == i[-1]:
count += 1
print(count)
只需取example
字符串,将其制成lower.()
进行比较,然后将其拆分,即可得到words
。
将每个word
变成一个list
并比较该list
的开头和结尾之后