TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python String | index() method with Examples

Python String index() method with Examples on capitalize(), center(), count(), encode(), find(), format(), index(), join(), lower(), ljust(), isupper(), istitle(), isspace(), isprintable(), isnumeric(), islower() etc.

<< Back to PYTHON

Python String index() Method

Python index() method is same as the find() method except it returns error on failure. This method returns index of first occurred substring and an error if there is no match found.

Signature

index(sub[, start[, end]])

Parameters

  • sub : substring
  • start : start index a range
  • end : last index of the range

Return Type

If found it returns an index of the substring, otherwise an error ValueError.

Let's see some examples to understand the index() method.

Python String index() Method Example 1

# Python index() function example
# Variable declaration
str = "Welcome to the TheDeveloperBlog."
# Calling function
str2 = str.index("at")
# Displaying result
print(str2)

Output:

18

Python String index() Method Example 2

An error is thrown if the substring is not found.

# Python index() function example
# Variable declaration
str = "Welcome to the TheDeveloperBlog."
# Calling function
str2 = str.index("ate")
# Displaying result
print(str2)

Output:

ValueError: substring not found

Python String index() Method Example 3

We can also pass start and end index as parameters to make process more customized.

# Python index() function example
# Variable declaration
str = "Welcome to the TheDeveloperBlog."
# Calling function
str2 = str.index("p",19,21)
# Displaying result
print("p is present at :",str2,"index")

Output:

p is present at : 20 index

Next TopicPython Strings




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf