簡體   English   中英

TypeError:'str'對象不可調用(Python 2)

[英]TypeError: 'str' object is not callable (python 2)

程序檢查單詞是否以相同字母開頭和結尾

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代碼,出現錯誤

Traceback (most recent call last):
  File "D:\Programming\Python\Python 2.7\same_letter.py", line 21, in <module>
    main()
  File "D:\Programming\Python\Python 2.7\same_letter.py", line 13, in main
    words_list = words_list().split()
TypeError: 'str' object is not callable

如果有人可以幫助我,我將非常感激。

這行有一個額外的括號

words_list = words_list().split()

可能只是

words_list = words_list.split()

實際上,您有許多無關的步驟,您的代碼塊

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']

Thanx Cyber​​ ..它為我工作。 這段代碼完全適合我的需要

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM