![](/img/trans.png)
[英]string indices must be integers error in python, but indices are integers
[英]Python strange “string indices must be integers” error
問題解決了! 是 newfilename[0,3] 而不是 newfilename[0: 3]
我知道以前有人問過這個問題,並且我已經查看了所有答案以及人們遇到的與此錯誤消息相關的問題類型,但找不到遇到相同類型問題的人。
我正在播種整個方法以防萬一。 所以這是我的問題;
當我嘗試使用 newfilename[int, int] 獲得“newfilename”的 substring 時,編譯器一直認為我沒有 integer 在那里,至少從我的檢查來看是這樣。
我正在用這段代碼做什么:我正在剪切文件名的結尾,例如“foo.txt”,以獲取保存為新文件名的“foo”。 然后我將數字(轉換為字符串)添加到它的末尾以獲得“foo 1”,然后添加回“.txt”以獲得“foo 1.txt”的最終結果。 當我嘗試取出 substring 並刪除文件名的最后四個字符以獲得“foo”時,就會出現問題。 之后,我再次檢查文件夾中是否還有類似的文件,如果有,我會進行另一組剪切和粘貼以將 1 添加到前一個文件中。 老實說,我還沒有測試過 while 循環是否可以工作,我只是認為它在技術上應該可以工作,但是由於這個錯誤,我的代碼並沒有達到那么遠,哈哈。
我的錯誤:
File "C:/Users/Reaper/IdeaProjects/Curch Rec Managment/Setup.py", line 243, in moveFiles
print(newfilename[0, 3])
TypeError: string indices must be integers
注意這個錯誤是從我試圖硬編碼它的數字看它是否會工作
這是注釋掉硬代碼的當前錯誤:
newfilename = newfilename[0, int(newfilename.__len__() - 4)] + " 1.m4a"
TypeError: string indices must be integers
我嘗試過的:我嘗試通過按字面輸入 newfilename[0, 7] 對數字進行硬編碼,但仍然出現相同的錯誤。 我曾嘗試在單獨的 python 文件中執行此操作,它似乎在那里工作正常。 此外,真正讓我感到困惑的是,它在我的程序的另一部分工作得很好,如下所示:
nyear = str(input("Enter new Year: "))
if nyear[0:2] != "20" or nyear.__len__() > 4:
print("Sorry incorrect year. Please try again")
所以我已經做了一段時間了,現在試圖弄清楚世界上正在發生什么而無法到達那里。 決定我會睡在上面,但會發布問題以防萬一。 如果有人能指出可能有什么問題,那就太棒了,或者告訴我編譯器只是愚蠢。 好吧,我想這也可以。
我的 function 代碼
def moveFiles(pathList, source, filenameList):
# moves files to new location
# counter keeps track of file name position in list
cnter = 0
for x in pathList:
filename = filenameList[cnter]
#print(x + "\\" + filename)
# new filename
if filename.find("PR") == 0:
newfilename = filename[3:filename.__len__()]
else:
newfilename = filename[2:filename.__len__()]
# checking if file exists and adding numbers to the end if it does
if os.path.isfile(x + "\\" + newfilename):
print("File Name exists!!")
# adding a 1 to the end
print(newfilename)
# PROBLEM ON NEXT TWO LINES, also prob. on any line with the following calls
print(newfilename[0, 3])
newfilename = newfilename[0, int(newfilename.__len__() - 4)] + " 1.m4a"
print("Adding 1:", newfilename)
# once again check if the file exists and adding 1 to the last number
while os.path.isfile(x + "\\" + newfilename):
# me testing if maybe i just can't have math operations withing the substring call
print("File exists again!!")
num = newfilename.__len__() - 6
num2 = newfilename.__len__() - 4
num3 = int(newfilename[num, num2])
num = newfilename.__len__() - 5
newfilename = newfilename[0, num] + str(num3 + 1)
print("Adding 1:", newfilename)
# moving file and deleting prefix
if not os.path.isdir(x):
os.makedirs(x)
os.rename(source + "\\" + filename, x + "\\" + newfilename)
cnter += 1
我認為你需要這個:
print(newfilename[0:3])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.