+ 1

Is it possible to use index() on a string?

I was wondering, b/c that many list functions can be used on strings, like list slicing and indexing, if index could be used on a string. I will be testing it in code playground, but it would also help to get some feedback. I recently created an indexing function from scratch for a code challenge, so it would be a relief to know whether I can use index() on a string.

16th Jun 2023, 11:32 PM
Jin
Jin - avatar
2 Answers
+ 4
Jin absolutely text = 'Python is fun' # find the index of is result = text.index('is') print(result) # Output: 7 or text = 'Is Python is fun for everyone' # find the index of Python result = text.index('Python is fun') print(result) # Output: 3
17th Jun 2023, 1:50 AM
BroFar
BroFar - avatar
+ 5
Jin , > an alternative way to index() could be the find() function. the reason for this is that python creates an error (ValueError) when the text (substring) can not be found in the string. > using find() will return *-1* in case of the substring can not be found. > if we have to stick with index() for what ever reason, we can use membership operator *in* first, to make sure that the index() function will work without problem. see a sample in the attached file: https://code.sololearn.com/cdZl16b0TJhX/?ref=app
17th Jun 2023, 10:52 AM
Lothar
Lothar - avatar