1. ホーム
  2. Python

AttributeError: 'function' オブジェクトに 'split' 属性がない Solution

2022-02-09 06:04:34
Reverse reading and reversing strings for #List
def reverseWords(input):
    #split the words in the sentence into a list by spaces
    inputWords = input.split(" ")
    print("Initial list: ",inputWords)
    # flip the sentence by reading the list of words from back to front
    inputWords = inputWords[-1::-1]# the first parameter means the last element of the list, the second parameter means move to the end, the third parameter means move from back to front 1 at a time
    print("flipped list: ",inputWords)
    # Reassemble the sentences according to the list
    output = ' '.join(inputWords)
    print("flipped sentences:",output)

    return output

input("Please input some words:")
rw = reverseWords(input)

上記のコードを実行した結果、報告されたエラーは以下の通りです。

Please input some words:Never Give Up !
Traceback (most recent call last):

  File "<ipython-input-10-73122fe302c8>", line 16, in <module>
    rw = reverseWords(input)

  File "<ipython-input-10-73122fe302c8>", line 3, in reverseWords
    inputWords = input.split(" ")

AttributeError: 'function' object has no attribute 'split'

解決策は input("Please input some words:") を input = input("Please input some words:") に変更することです。

修正したコードは以下の通りです。

Reverse reading of #List and reversing strings
def reverseWords(input):
    #split the words in the sentence into a list by spaces
    inputWords = input.split(" ")
    print("Initial list: ",inputWords)
    # flip the sentence by reading the list of words from back to front
    inputWords = inputWords[-1::-1]# the first parameter means the last element of the list, the second parameter means move to the end, the third parameter means move from back to front 1 at a time
    print("flipped list: ",inputWords)
    # Reassemble the sentences according to the list
    output = ' '.join(inputWords)
    print("flipped sentences:",output)

    return output

input = input("Please input some words:")
rw = reverseWords(input)

結果を実行します。

Please input some words:Never Give Up !
Initial list: ['Never', 'Give', 'Up', '!]
flipped list: ['! , 'Up', 'Give', 'Never']
Flipped sentences: ! Up Give Never