2015-09-25 70 views
1

此代碼以前工作,但現在給我的問題。獲取類型錯誤,我找不到原因

def stringsAreFun(): 
string1 = input("Enter a String you want to modify: ") #stores the user imput to string1 variable 
stringLength = len(string1) #stores stringlen to a variable for future, repitive calls 
print("The length is ", stringLength) 
print("The first character is " + string1[0] 
+ " and the last character is " + string1[stringLength - 1]) 
listString = list[string1] 
if stringLength >= 6: 
    #creates a list of characters from string1 because strings are immuntable in python 
    #http://www.tutorialspoint.com/python/python_lists.htm 
    listString[stringLength - 1] = 'C' 
    listString[stringLength - 2] = 'B' 
    listString[stringLength - 3] = 'A' 
    print(''.join(listString)) #joins the list(x) into a string to be printed 
    #http://www.tutorialspoint.com/python/string_join.htm 
if stringLength >= 6: 
    listString[0] = 'X' 
    listString[1] = 'Y' 
    listString[2] = 'Z' 
    print(''.join(listString)) 

if stringLength >= 2 & stringLength <= 5: 
    listString[0] = '1' 
    print(''.join(listString)) 
if stringLength >= 2 & stringLength <= 5: 
    listString[stringLength - 1] = '0' 
    print(''.join(listString)) 

if stringLength % 2 == 0: 
    print("The length of the string is an even number!") 

else: 
    print("The length of the string is an odd number") 

我m如果此輸出:

TypeError: 'type' object is not subscriptable 
+0

將來,添加有關發生異常的行的信息。這意味着更少的猜測和更快的答案。 – viraptor

回答

1

這條線:

listString = list[string1] 

不會做你想做的。

listString = list(string1) 
+0

哇謝謝你。我想這是當你盯着8小時的代碼時會發生什麼。 – WonderphuL

0

它應該是list(string1)而不是list[string1]。後者是下標(與[]type對象list,它會產生您看到的錯誤。

0

我猜你的意思是string1轉換爲list,當你嘗試過這條線 -

listString = list[string1] 

問題是list()是一個內置的類型,你需要把它傳遞string1作爲參數。示例 -

listString = list(string1)