×

Find Words in String Python

Python :

Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in libraries that can be imported easily and used to perform many different kinds of operations; to import these libraries or to use these libraries; we need to install a package called python installation package ( pip ). Python has considered an object-oriented programming language with code and data; the data in the object-oriented program is in terms of attributes, and the code is in terms of methods or functions. In the year 1989, Guido van Rossum is the one who introduced python programming language. Python is an interpreted programming language; Python 3.0 was released in 2016 and is mainly used by many companies. Python is widely used in machine learning, and data science departments deal with heavy data. It is also used in web applications; web applications like the Django and Flask frameworks are created using python. The python programming language is straightforward to learn by anyone. Compared to any programming language, the syntax in python is much easier. Many colleges and institutions have introduced python in their syllabus so that the students need to learn python.

Strings in python

Strings are defined as the collection of characters, or it is the array of bytes depicting characters. In a python programming language, it does not have a datatype called a character; a single character is said to be considered a string of length 1. We can access each element from the string using square brackets and its respective index. In python programming language, strings are created using single quotes ( ‘ ’ ), double quotes ( “ ” ), and even triple quotes ( ‘ ‘ ‘ ’ ’ ’ ). The advantage of using triple quotes is it allows multiple lines of a string. Now, let us look into an example program on how strings are created in python 3.

Example program :

# # # program for creating a string in python 
# # # creating a string using single quotes 
S = 'welcome to marvel cinematic universe.'
print('creating a string using single quotes: ' )
print(S)
# # # creating a string using double quotes
S = ' I\'m IRON MAN '
print( 'creating a string using double quotes:' )
print(S)
# # # creating a string using triple quotes
S = ''' I'm IRON MAN and I belong to the "marvel universe"'''
print( " creating string using triple quotes: " )
print(S)
# # # creating a multi-line string using triple quotes
S = ''' avengers
        ASSEMBLE '''
print( " creating a multi-line string using triple quotes: " )
print(S)

Output 

creating a string using single quotes: 
welcome to marvel cinematic universe.
creating a string using double quotes:
 I'm IRON MAN 
 creating string using triple quotes: 
 I'm IRON MAN and I belong to the "marvel universe"
 creating a multi-line string using triple quotes: 
 avengers
        ASSEMBLE

How to access a character or element from a string in python

In a python programming language, the characters of the string are accessed using a process called indexing. The first character is indexed as 0; the second character is indexed as 1, and so on. Now, to access the last character, the last character is indexed as -1, the last second character is indexed as -2, and so on. Each character in the string is indexed with an integer, and indexing with other data types shows a type error.

Example program:

# # # program for accessing the character of a string 
# # #creating a string
S= "marvelUniverse"
print( S )


# # # accessing the first element of string using indexing
print( "the first character of string is:" )
print( S[ 0 ] )
# # # accessing the last element of the string using indexing
print( "last character of string is:" )
print( S[ -1 ] )
# # # accessing last second element of string using indexing
print( S[ -2 ] ) 

Output

marvelUniverse
the first character of string is:
m
last character of string is:
e
s

Find words in string python.

Now let us discuss how to find words in a string in a python programming language.

Python string find() method is used to find the word in a string in a python programming language. This method returns the lowest index of a given string or the initial occurrence of the substring found in the string. If not, it returns -1 

The syntax for this method is given as follows

Syntax:

string_obj.find(sub, start, end)

The parameters involved in this method are sub, return, start, and end, which is considered optional.

Sub: This parameter is called substring, searched in the given string.

Start( optional ): This parameter defines the starting position where the substring is to be checked within the declared string.

End( optional ): This parameter defines the ending position, the index of the end position for the specified range. It is supposed to be excluded while checking.

Return: This parameter returns the lowest substring index if found in the declared substring. If the substring is not found, it returns -1 to the programmer.

Now let us look into an example of the python string find() method

Example code:

# # # creating a string in a python programming language
S = " bring me thanos "
print( S )
print( S.find( 'me' ) )

Output

bring me thanos
7

If the start and end indexes are not provided, then it takes 0 ans -1 as the length of the start and end indexes. The find( ) method is considered similar to the index( ) method; the only difference between these two methods is that the find method returns -1 to the user or programmer if the search is not found. The index method, in this case, shows an exception to the user or programmer.

Now let us find the word with no starting and ending indexes

Example code:

# # # creating a string in a python programming language
S = "bring me thanos "
print( S )
# # # returning the first occurrence of a substring
res = S.find( ' bring ' )
print( " substring 'bring' found at the index: ", res )
res = S.find( 'me' )
print(" substring 'me' found at the index: ", res )
# # # Now lets use find( )
if S.find( ' ironman' ) != -1 :
      print( " contains the given substring " )
else :
      print( " doesn’t contains the substring " )

Output

bring me thanos
substring ‘bring’ found at the index : 0
substring ‘me’ found at the index: 1
 doesn’t contains the substring

 Now let us look into the example which has to start and end arguments

In this example, the user or programmer specifies the starting and ending arguments of the string find( ) method. Now it searches the substring in the declared original string.

Example code

# # # creating a string in a python programming language
S = " bring me thanos "
print( S )
# # # substring is searched in ‘ng me thanos.’
print( S.find( 'tha' ,2 ) )
# # # substring is searched in ‘ng me thanos.’
print(S.find( 'br', 2 ) )

Output

bring me thanos
10
-1

In the first case, the output is 8 as the start value is given as 2, so it starts checking from the second index of the declared substring. If the substring is found, it returns the index at what position it has been; if it is not found, it would have a return of -1. In the second case, the substring is ‘br’. It is searched from the second index as the starting value is given as 2, but the output is returned as -1 because there is no substring. Hence it returns -1.


Related Topics

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.