Find a specific word location in a string

Asked 2 years ago, Updated 2 years ago, 134 views

Is there a method like java's contents or indexOf? I'm going to write it like this.

if not somestring.contains ("String to Find"):
   continue

string python substring contains

2022-09-22 22:33

1 Answers

string.found() supports this feature. string.found(substring) returns the starting index if substring exists, and -1 if not.

st1 = "Hello World!"
st2 = "World"
idx = st1.find(st2)
if idx==-1:
    print('not exist')
else:
    print('exist at idx', idx)

You can use it with .

You can use the "in" operator if you want to determine only the presence or absence.

st1 = "Hello World!"
st2 = "World"
if st2 in st1:
    print('exist')
else:
    print('not exist')


2022-09-22 22:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.