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:
-
Have Questions? Post them here!
More Posts related to Python,
- Check version of pip package installer for Python
- How to install Python 3.9 using brew on Mac
- Python Program To Calculate Simple Interest (SimpleInterest.py)
- Indent Python code in Notepad++
- Change label (text) color in tkinter
- Float built-in function in Python
- [Fix] ValueError: substring not found in Python
- pip get list of all outdated Python packages
- Calculate discount amount python code
- 3 Python program to add two numbers
- How to List all Packages installed using pip [Python]
- Python range() function examples
- How to resolve Failed to create interpreter PyCharm Error
- Format Python Code in Visual Studio Code (VS Code)
- Validate email address in Python using regular expression (regex)
- Install and Run Jupyter Notebook on Mac (macOS)
- How to delete a file using Python code example
- Base64 Encoding Decoding in Python Programming
- How to pip install Python Modules in VSCode
- Change the background of Tkinter label or text
- Comments in Python Programming
- Take input argument from command line in Python Programming
- How to Convert Python String to DateTime Object
- Tkinter - add x and y padding to label text
- [Tutorial] Install Python on Visual Studio Code (VS Code)
More Posts:
- How to clear Cache, Cookies and History on iPhone Safari - iOS
- Command to check Last Login or Reboot History of Users and TTYs - Linux
- Detect if Cookies are enabled using JavaScript - JavaScript
- Hyperlink in html (anchor tag) without a underline - Html
- How to Refresh Mac Desktop - MacOS
- DDMS files not found hprof-conv.exe - Android
- Multiple Microsoft 365 Services Down (Outlook, Teams, SharePoint, OneDrive) - 25 January 2023 (Solved) - Microsoft
- How to find the path of formula Installation by Brew - HowTos