Victor
Victor

Reputation: 9

How to extract string in Python

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

Answers (4)

mertyildiran
mertyildiran

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

Chris0710
Chris0710

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

Vinícius Figueiredo
Vinícius Figueiredo

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

ElephantErrors
ElephantErrors

Reputation: 3

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

Upvotes: 0

Related Questions