TypeError:“str”对象不可调用(python 2)

2024-05-21 08:43:28 发布

您现在位置:Python中文网/ 问答频道 /正文

检查单词是否以相同字母开头和结尾的程序

def match_letter():
    count = 0
    for word in words:
        if len(word) >=2 and word[0] == word[-1]:
            count = count + 1
    return count

def main():
    words = []
    words_list = raw_input('Enter Words: ')
    words_list = words_list().split()
    for word in words_list:
        words.append(word)

    count = match_letter()
    print 'letter matched %d ' %count

if __name__ == '__main__':
    main()

这是我的python代码,给出了一个错误

^{pr2}$

如果有人能帮助我,我非常感激。。在


Tags: in程序forifmaindefmatchcount
2条回答

Thanx赛博。。对我有用。 这个代码完全符合我的要求

def match_letter(words):
    count = 0
    for word in words:
        if len(word) >=2 and word[0] == word[-1]:
            count = count + 1
    return count

def main():
    words = raw_input('Enter Words: ').split()
    count = match_letter(words)
    print 'letter matched %d ' %count

if __name__ == '__main__':
    main()

这一行有一个额外的圆括号

words_list = words_list().split()

可能只是

^{pr2}$

实际上,你有很多无关的步骤,你的代码块

words = []
words_list = raw_input('Enter Words: ')
words_list = words_list().split()
for word in words_list:
    words.append(word)

可以简化为:

words = raw_input('Enter Words: ').split()

如果我理解你的问题,我会用切片来解决这个问题

def same_back_and_front(s):
    return s[0] == s[-1]   # first letter equals last letter

>>> words = ['hello', 'test', 'yay', 'nope']
>>> [word for word in words if same_back_and_front(word)]
['test', 'yay']

相关问题 更多 >