TypeError: list indices must be integers or slices, not str Problem


#1

how do you delete posts?


#2

This just means your for loop is saying it cannot iterate index by index over type string arguments,

If you are new to coding, I suggest writing your code in small parts. File handling is a tad bit more technical so start by storing these uniquewords_ and origsntnce_ in variables, and when that is working for you feel free to ask about how to store it in files and I or any other Help Desker who verses in Python will be happy to help. :grin:


#4

Could you try running it please and let me know what you think is the problem.


#5

Since you are handling a string you could use the . split() method and then now modify the string,

Also using print statements in between lines helps you see what your code is doing as to what you would like it do.


#6

This is the problem,


#7

Thank you again for the reply, so if I was to use the .split() command what section exactly would I need to split the unique_words or positions? Also, what do I need to split it by? Like split it by (" ")? Or something?


#8

So how do I convert string to 'slice'? Or how do I fix this problem here?


#9

The .split() method does not convert strings, but slices them for example,

x = 'x,y,z'
x.split(",")

['x', 'y', 'z']

After converting it into a list you can modify it however you like and then print it pretty using the ''.join() method


#10

Hmm... I need to be able to keep the capitalisation and punctuation of the original sentence. I don't think I can do this when using the split() command.


#11

Punctuation and Capitalisation will still be preserved all you are doing is this let say you have a sentence,

word = "This is some random text"

That sentence split,

['This', 'is', 'some', 'random', 'text']


#12

Okay I think I'm starting to understand.

But when I: print(uqwordsFile)

I get for example ['the', 'cat', 'sat', 'on', 'mat']

And this doesn't work with:
for l in positions_File:
orig_sntnce.append(uqwordsFile[l])
print(orig_sntnce)

This is the point where I am confused, I cannot split the list can I? As if I did then this would mean I would lose capitalisation and punctuation?


#13

ok then this is good your string has already been split, now the question is what are you trying to achieve by looping through, positions_File


#14

I want to re-create the original user sentence through unique individual words and positions.

Unique words will be all the unique words from the user's sentence, so for example "the cat sat on the mat" the unique words will be "the, cat, sat, on, mat" and the positions will be 123415.

So the loop should re-create the original sentence of the user's, from the positions and unique words. But when I run this loop I get the error.


#15

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.