myStr = "I love Python!"
myStr.index('x')
Error:
ValueError Traceback (most recent call last)
Cell In[38], line 3
1 myStr = "I love Python!"
----> 3 myStr.index('x')
ValueError: substring not found
Error in PyCharm:
Traceback (most recent call last):
File "/Users/code2care/PycharmProjects/python-learnings/Strings.py", line 3, in <module>
myStr.index('cool')
ValueError: substring not found
Process finished with exit code 1
Reason for this error
"ValueError: substring not found" error will occur when you make use of the index() function on a string to get a substring, but the substring is not found.
To fix this issue while working with the index() function have a if conditional check to see if a substring exists before using the index() function.
Example:myStr = "I love Python!"
subStr = "cool"
if subStr in myStr:
print(myStr.index(subStr))
else:
print(f"Substring '{subStr}' not found in string '{myStr}'")
Output:
Substring 'cool' not found in the string 'I love Python!'
Code Screenshot:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!