[Fix] ValueError: substring not found in Python


Code Example:
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:
Python ValueError - substring not found and how to fix it

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap