0

I want to extract specific string from a string, but it shows error. Why can't I use the find as index to extract string ?

Here is my code

string = 'ABP'
p_index = string.find('P')
s = string[0, p_index]
print(s)

TypeError: string indices must be integers

4 Answers 4

1

s = string[0, p_index] isn't a valid syntax in python, you should rather do:

s = string[0:p_index]

Since an omitted first index defaults to zero, this returns the same result:

s = string[:p_index]

I'd recommend reading this page for reference on Python string's slicing and it's syntax in general.

Sign up to request clarification or add additional context in comments.

Comments

1

You should change this line:

s = string[0, p_index]

with

s = string[p_index]

You don't need to put anything rather than the index of the letter to get 'P' and you found the index with string.find('P') already.

If you mean substracting the 'P' letter from 'ABP' then use:

new_string = 'ABP'.replace('P','')

Comments

0

I'm pretty sure you slice strings like this s = string[0:2]

Comments

0
string = 'ABP'
p_index = string.index('P')
s = string[p_index]
print(s)

string = 'ABP'
p_index = string.find('P')
s = string[p_index]
print(s)

maybe you can try it like this two

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.