Reputation: 9
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
Upvotes: 0
Views: 7774
Reputation: 6613
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','')
Upvotes: 1
Reputation: 17
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
Upvotes: 0
Reputation: 6518
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.
Upvotes: 1