How to Find the Index of a String in Python

The open-source programming language Python is known for the readability of its code and the ability to extend the language by adding C modules. At times, you may need to find the index of a string. For example, when programming a Web application, you may want to check that users do not enter an invalid URL or unacceptable term in a comments field. To find the index of a string, you use the "str.index" function. This function is similar to "find ()", but "str.index" returns an error if the string is not found.

Instructions

    • 1

      Access your Python editor.

    • 2

      Type:

      x = "This is a string example"

      x.index ('exam')

    • 3

      Press "Enter".

      Python returns "17".

      In this example, 17 is the number of characters in string "x" when the phrase "exam" appears. That is, 17 characters occur in the string before you encounter the substring "exam." Note that if you had entered x.index ('exa'), x.index ('ex') or x.index ('examp'), Python would still have returned "17."

      If the phrase does not appear in the string. Python returns "ValueError: substring not found." In the example above, "x.index ('foo') returns a "substring not found" error.

Related Searches:

References

Comments

Related Ads

Featured