Python

Python Program to Read a File and Capitalize the First Letter of Every Word in the File

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Files in Python:

A file is a piece of information or data that is kept in computer storage devices. You are already familiar with several types of files, such as music files, video files, and text files. Python makes it simple to manipulate these files. In general, files are classified into two types: text files and binary files. Text files are plain text, whereas binary files include binary data that can only be read by a computer.

Python file handling (also known as File I/O) is an important topic for programmers and automation testers. It is necessary to work with files in order to either write to or read data from them.

Furthermore, if you are not already aware, I/O operations are the most expensive procedures through which a program might fail. As a result, you should take caution while implementing file handling for reporting or any other reason. Optimizing a single file activity can contribute to the development of a high-performance application or a solid solution for automated software testing.

Given  a file, thee= task is to read the given file and capitalize the first letter of every word in the given file

Program to Read a File and Capitalize the First Letter of Every Word in the File

Below is the full process Read a File and Capitalize the First Letter of Every Word in the File.

Approach:

  • Create the file or upload the existing file.
  • Enter the file name of the file using the input() function and store it in a variable.
  • In read mode, open the file with the entered file name.
  • Using for loop, go over the lines in the first file.
  • To capitalize each word in the line, use the title() function.
  • Print the file’s modified lines.
  • The exit of the program.

Below is the implementation:

# Enter the file name of the first file using the input() function and store it in a variable.
filename = input("Enter the first file name = ")
# In read mode, open the first file with the entered file name.
with open(filename, 'r') as givenfile:
  # Using for loop, go over the lines in the first file.
    for fileline in givenfile:
      # To capitalize each word in the line, use the title() function.
        line = fileline.title()
        # Print the file's modified lines.
        print(line)

Explanation:

  • A file name needs to be entered by the user.
  • The file is opened in reading mode with the open() function.
  • To read every line in the file, a for loop is needed.
  • The title() method is used to capitalize every word in the line.
  • The modified lines will be printed.

Output:

Before Modifying:

Python is a high-level, object-oriented, interpretable, dynamic semantic programming language.
Its high-level data structures, along with dynamic typing and dynamic connections are particularly 
interesting both for the development of rapid application and for the usage as a script or glue language 
in connecting existing components. The basic, easy syntax of Python underlines readability and hence saves 
software maintenance costs.
Python allows modules and packages, which promote the modularity of the programme and the reuse of code.
The Python interpreter and the vast standard library can be freely supplied, either as a source or as a binary,
for all major platforms without payment.The improved productivity of programmers is often a result of the love of Python.
The edit-test-debug cycle is extraordinarily rapid, given there is no compilation stage. It is easy to debug 
Python programmes: a bug or poor input never causes segmentation errors. Rather, it does raise an exception when the
interpreter discovers an error. The tracer prints a stack track if the programme does not catch the exception.
A source level debugger allows you to check local and global variables, evaluate arbits, set breakpoints, 
line by line code, and so on. A source level debugger is available. The debugger is written in Python, 
showing the introspective power of Python. On the other hand, the most easy way of debugging a programme often is to
add several print statements to the source: this basic approach has a fast editing-test-debug cycle.

After Modifying:

Enter the first file name = samplefile1.txt
Python Is A High-Level, Object-Oriented, Interpretable, Dynamic Semantic Programming Language.
Its High-Level Data Structures, Along With Dynamic Typing And Dynamic Connections Are Particularly
Interesting Both For The Development Of Rapid Application And For The Usage As A Script Or Glue Language
In Connecting Existing Components. The Basic, Easy Syntax Of Python Underlines Readability And Hence Saves
Software Maintenance Costs.
Python Allows Modules And Packages, Which Promote The Modularity Of The Programme And The Reuse Of Code.
The Python Interpreter And The Vast Standard Library Can Be Freely Supplied, Either As A Source Or As A Binary,
For All Major Platforms Without Payment.The Improved Productivity Of Programmers Is Often A Result Of The Love Of Python.
The Edit-Test-Debug Cycle Is Extraordinarily Rapid, Given There Is No Compilation Stage. It Is Easy To Debug
Python Programmes: A Bug Or Poor Input Never Causes Segmentation Errors. Rather, It Does Raise An Exception When The
Interpreter Discovers An Error. The Tracer Prints A Stack Track If The Programme Does Not Catch The Exception.
A Source Level Debugger Allows You To Check Local And Global Variables, Evaluate Arbits, Set Breakpoints,
Line By Line Code, And So On. A Source Level Debugger Is Available. The Debugger Is Written In Python,
Showing The Introspective Power Of Python. On The Other Hand, The Most Easy Way Of Debugging A Programme Often 
Is To Add Several Print Statements To The Source: This Basic Approach Has A Fast Editing-Test-Debug Cycle.

Google Colab Images:

Files and Code:

Code:

Output Image:

Sample file:

Related Programs:

Python Program to Read a File and Capitalize the First Letter of Every Word in the File Read More »

Program to Append the Contents of One File to Another File

Python Program to Append the Contents of One File to Another File

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Files in Python:

A file is a piece of information or data that is kept in computer storage devices. You are already familiar with several types of files, such as music files, video files, and text files. Python makes it simple to manipulate these files. In general, files are classified into two types: text files and binary files. Text files are plain text, whereas binary files include binary data that can only be read by a computer.

Python file handling (also known as File I/O) is an important topic for programmers and automation testers. It is necessary to work with files in order to either write to or read data from them.

Furthermore, if you are not already aware, I/O operations are the most expensive procedures through which a program might fail. As a result, you should take caution while implementing file handling for reporting or any other reason. Optimizing a single file activity can contribute to the development of a high-performance application or a solid solution for automated software testing.

Program to Append the Contents of One File to Another File

Below is the full process to append the contents of one file to another file.

Approach:

  • Create the first file or upload the existing file.
  • Create the second file or upload the existing file.
  • Enter the file name of the first file using the input() function and store it in a variable.
  • In read mode, open the first file with the entered first file name.
  • Enter the file name of the second file using the input() function and store it in another variable.
  • In append mode, open the second file with the above-entered second file name.
  • Read the first file using the read() function and store it in a variable.
  • Close the first file using close() function.
  • Append the contents of the first file using the write() function.
  • Close the second file using close() function.
  • The exit of the program.

Below is the implementation:

# Enter the file name of the first file using the input() function and store it in a variable.
filename1 = input("Enter the first file name = ")
# Enter the file name of the second file using the input() function and store it in another variable.
filename2 = input("Enter the second file name = ")
# In read mode, open the first file with the entered file name.
file1 = open(filename1, "r")
# Read the first file using the read() function and store it in a variable.
filedata1 = file1.read()
# Close the first file using close() function.
file1.close()
# In append mode, open the second file with the above-entered second file name.
file2 = open(filename2, "a")
# Append the contents of the first file using the write() function.
file2.write(filedata1)
file2.close()

Explanation:

  • The user must provide the file to be read from and the file to append to.
  • In read mode, the file to be read is opened with the open() function.
  • The contents of the file read with the read() function are saved in a variable, and the file is then closed.
  • The file to which the data will be appended is opened in append mode, and the data stored in the variable is written into it.
  • After then, the second file is closed.

Output:

Before Appending:

Samplefile1.txt:

By now you might be aware that Python is a Popular Programming Language used 
right from web developers to data scientists. Wondering what exactly Python looks
like and how it works? The best way to learn the language is by practicing. We have listed a wide 
collection of Python Programming Examples.You can take references 
from these examples and try them on your own.

Samplefile2.txt:

hello this is btechgeeks

After Appending:

Samplefile1.txt:

By now you might be aware that Python is a Popular Programming Language used 
right from web developers to data scientists. Wondering what exactly Python looks
like and how it works? The best way to learn the language is by practicing. We have listed a wide 
collection of Python Programming Examples.You can take references 
from these examples and try them on your own.

Samplefile2.txt:

hello this is btechgeeksBy now you might be aware that Python is a Popular Programming Language used 
right from web developers to data scientists. Wondering what exactly Python looks
like and how it works? The best way to learn the language is by practicing. We have listed a wide 
collection of Python Programming Examples.You can take references 
from these examples and try them on your own.

Google Colab Images:

Files and Code:

Samplefile2.txt:

Samplefile1.txt:

Files in Python:

Python, like many other programming languages, offers file handling and allows users to read and write files, as well as perform a variety of other file-related tasks. The concept of file handling has been extended to a variety of other languages, but the implementation is either complicated or lengthy. However, like most Python principles, this concept is simple and straightforward. Python processes file differently depending on whether they are text or binary, which is crucial. Each line of code consists of a series of characters that together constitute a text file. A specific character called the EOL or End of Line character, such as the comma, or a newline character is used to end each line in a file.

Given a file, the task is to read the given text file and print all the numbers present in the given text file.

Program to Read a Text File and Print all the Numbers Present in the Text File

Below is the full process to read a text file and print all the numbers present in the given text file.

Approach:

  • Create the sample file or upload the existing file.
  • In read mode, open the first file say  samplefile.txt.
  • Using for loop, go over the lines in the sample file.
  • Split the line into words using the split() function.
  • Traverse through the words using for loop.
  • Traverse through all the characters of the word using another For loop.
  • Check to see if the letter is a digit, and if so, print it.
  • Exit of program

Below is the implementation:

filename = input('Enter the name of the given file : ')
# In read mode, open the given file with the name 'filename'
with open(filename, 'r') as file:
  # Using for loop, go over the lines in the sample file.
    for line in file:
      # Split the line into words using the split() function.
        words = line.split()
        # Traverse through the words using for loop.
        for i in words:
          # Traverse through all the characters of the word using another for loop.
            for letter in i:
              # Check to see if the letter is a digit, and if so, print it.
                if(letter.isdigit()):
                    print(letter)

Output:

Enter the name of the given file : samplefile.txt 
 1
 1
 2
 3
 9
 4
 5
 6
 7
 9
 8
 3
 3

Explanation:

  • A file name must be entered by the user.
  • In read mode, the file is opened with the open() method.
  • To read each line in the file, a for loop is utilized.
  • Using split, each line is divided into a list of words ().
  • The word list is traversed using a for loop, and the letters of the word are traversed using another For loop.
  • The digit is printed if the letter encountered is a digit.
  • Here it prints all the digits present in the given file separately in a newline.

Sample file.txt :

hel11l2o th3is i9s B4TechGe5eks Onl6ine Cod7ing Platf9orm fo8r Bt3ech Stude3nts

Google Colab Images:

File and Code:

 

Output Image:

 

File Content:

Related Programs:

Python Program to Append the Contents of One File to Another File Read More »

Program to Count the Number of Lines in a Text File

Python Program to Count the Number of Lines in a Text File

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Files in Python:

Python File handling is a method that allows you to save the program’s output to a file or read data from a file. In the programming world, file handling is a critical notion. File management is employed in practically every type of project. For example, suppose you’re developing an inventory management system. You have data connected to sales and purchases in the inventory management system, thus you must save that data somewhere. You can save that data to a file using Python file management. If you want to undertake data analysis, you must be given data in the form of a comma-separated file or a Microsoft Excel file. You can read data from a file and also store output back into it using file handling.

Given a file, the task is to count the entire number of lines within the given file in Python.

Program to Count the Number of Lines in a Text File

Below is the full approach to count the total number of lines in the given text file.

Approach:

  • Take a variable that stores the count of the number of lines in a given file and initialize it to 0.
  • Create the file or upload the existing file.
  • Enter the file name of the file using the input() function and store it in a variable.
  • In read mode, open the file with the entered file name.
  • Using for loop, Traverse the lines in the file.
  • Increment the value of line count by 1.
  • Print the line count.
  • Exit of Program

Below is the implementation:

# Take a variable that stores the count of a number of lines in a given file and initialize it to 0.
linecount = 0
# Enter the file name of the  file using the input() function and store it in a variable.
filename = input("Enter the file name = ")
# In read mode, open the file with the entered file name.
with open(filename, 'r') as givenfile:
    # Using for loop, Traverse the lines in the file.
    # Increment the value of line count by 1.
    for line in givenfile:
        linecount = linecount+1
# Print the line count.
print('The total number of lines in the given file = ', linecount)

Output:

Enter the file name = hello.txt 
The total number of lines in the given file = 7

Explanation:

  • A file name must be entered by the user.
  • In read mode, the file is opened with the open() method.
  • To read through each line of the file, a for loop is utilized.
  • Each time, the line count is incremented, and the total count is printed using the print() function.

File Content:

Python File handling is a method that allows you to save the program's output to a file or read data from a file. 
In the programming world, file handling is a critical notion. File management is employed in practically every type 
of project. For example, suppose you're developing an inventory management system. You have data connected to sales 
and purchases in the inventory management system, thus you must save that data somewhere. You can save that data to a
file using Python file management. If you want to undertake data analysis, you must be given data in the form of a 
comma-separated file or a Microsoft Excel file. You can read data from a file and also store output back into it using 
file handling.

Google Colab Images:

Files and Code:

Code:

Output Image:

Hello.txt

 

 

 

 

 

Python Program to Count the Number of Lines in a Text File Read More »

Program to Remove all Consonants from a String

Python Program to Remove all Consonants from a String

Given a string, the task is to remove all consonants present in the given string in Python.

Examples:

Example1:

Input:

Given string = 'HellothisisBTechGeeks '

Output:

The given string before removing consonants is [ HellothisisBTechGeeks ]
The given string after removing consonants is [ eoiieee ]

Example2:

Input:

Given string = 'goodmorningthisisbtechgeeks '

Output:

The given string before removing consonants is [ goodmorningthisisbtechgeeks ]
The given string after removing consonants is [ oooiiieee ]

Program to Remove all Consonants from a String in Python

Below are the ways to remove all consonants present in the given string in Python.

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Method #1: Using remove() method (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Convert this string to a list of characters using the list() function say charsstringlist.
  • Give the vowels as the list of characters(lowercase and uppercase) say vowelslst.
  • Traverse the charsstringlist using For loop(by taking list(charsstringlist) as we remove the list elements we need a temporary list)
  • Check if the iterator character is not present in vowelslst(which means it is consonant) using not in and If operator.
  • If it is true then remove the character from the charsstringlist.
  • Join the charsstringlist using the join() function.
  • Print the string after removing the consonants.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'HellothisisBTechGeeks'
print('The given string before removing consonants is [', gvnstrng, ']')
# Convert this string to a list of characters using
# the list() function say charsstringlist.
charsstringlist = list(gvnstrng)
# Give the vowels as the list of characters(lowercase and uppercase) say .
vowelslst = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
# Traverse the charsstringlist using For loop(by taking list(charsstringlist)
# as we remove the list elements we need a temporary list)
for itrchar in list(charsstringlist):
        # Check if the iterator character is not present in
    # vowelslst(which means it is consonant) using not in and If operator.
    if itrchar not in vowelslst:
        # If it is true then remove the character from the charsstringlist.
        charsstringlist.remove(itrchar)
# Join the charsstringlist using the join() function.
modifiedstrng = ''.join(charsstringlist)
# Print the string after removing the consonants.
print('The given string after removing consonants is [', modifiedstrng, ']')

Output:

The given string before removing consonants is [ HellothisisBTechGeeks ]
The given string after removing consonants is [ eoiieee ]

Method #2: Using remove() method (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Convert this string to a list of characters using the list() function say charsstringlist.
  • Give the vowels as the list of characters(lowercase and uppercase) say vowelslst.
  • Traverse the charsstringlist using For loop(by taking list(charsstringlist) as we remove the list elements we need a temporary list)
  • Check if the iterator character is not present in vowelslst(which means it is consonant) using not in and If operator.
  • If it is true then remove the character from the charsstringlist.
  • Join the charsstringlist using the join() function.
  • Print the string after removing the consonants.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvnstrng = input('Enter some random string to remove consonants = ')
print('The given string before removing consonants is [', gvnstrng, ']')
# Convert this string to a list of characters using
# the list() function say charsstringlist.
charsstringlist = list(gvnstrng)
# Give the vowels as the list of characters(lowercase and uppercase) say .
vowelslst = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
# Traverse the charsstringlist using For loop(by taking list(charsstringlist)
# as we remove the list elements we need a temporary list)
for itrchar in list(charsstringlist):
        # Check if the iterator character is not present in
    # vowelslst(which means it is consonant) using not in and If operator.
    if itrchar not in vowelslst:
        # If it is true then remove the character from the charsstringlist.
        charsstringlist.remove(itrchar)
# Join the charsstringlist using the join() function.
modifiedstrng = ''.join(charsstringlist)
# Print the string after removing the consonants.
print('The given string after removing consonants is [', modifiedstrng, ']')

Output:

Enter some random string to remove consonants = goodmorningthisisbtechgeeks
The given string before removing consonants is [ goodmorningthisisbtechgeeks ]
The given string after removing consonants is [ oooiiieee ]

Related Programs:

Python Program to Remove all Consonants from a String Read More »

Program to solve Maximum Subarray Problem using Kadane’s Algorithm

Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm

The maximum sub-array sum situation needs you to identify a continuous sub-array that has the highest sum.

Take a look at the following array:

The sum of a continuous array of green cells, i.e., 6, gives the greatest sum in this array of length 7 that is  Any other possible sub-array generates a sum that is less than or equal to 6.

The Maximum Subarray Problem is a well-known dynamic programming problem. Kadane’s algorithm is the algorithm we utilize to tackle this problem. It is a bit difficult algorithm to grasp, but don’t worry. In this tutorial, we will go over the algorithm in a simple manner.

Examples:

Example1:

Input:

given array = [-3, 4, 1, 2, -1, -4, 3]

Output:

The maximum subarray sum of the given list [-3, 4, 1, 2, -1, -4, 3] :
7

Example2:

Input:

given array  = [2, -1, 46, 9, -3, -2, 10, 11, -9, 23, -3]

Output:

The maximum subarray sum of the given list [2, -1, 46, 9, -3, -2, 10, 11, -9, 23, -3] :
86

Program to solve Maximum Subarray Problem using Kadane’s Algorithm in Python

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

1)Algorithm

Kadane’s approach is the best solution for finding the maximum sub-array; it utilizes two variables:

current_maximum to keep track of whether the value at the current index raises the maximum total.

maximum_so_far to keep track of the total maximum propagated along with the array.

  • Set both of the variables specified above to the value at the first index, i.e., arr[0].
  • Store the maximum of arr[i] and current_maximum + arr[i] in the current_maximum for the following index i.
  • Maximum_so_far stores the maximum of maximum_so_far and current_maximum.
  • Repeat the preceding two procedures for the remaining indices.
  • Return the maximum_so_far value.

2)Implementation(Static Array)

Approach:

  • Give the array/list as static input and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Pass the given list and length of the given list as an argument to the findKadane function which implements the kadane’s algorithm.
  • It returns the maximum subarray sum for the given list.
  • Print the maximum sum.
  • The Exit of the Program

Below is the implementation:

def findKadane(givnList, listleng):
    # Set both of the variablesto the value at the first index, i.e., givnList[0].
    cur_maxi = givnList[0]
    maxi_so_far = givnList[0]

    for i in range(1, listleng):
      # Store the maximum of givnList[i] and cur_maxi + givnList[i]
      # in the cur_maxi for the following index i.
        cur_maxi = max(givnList[i], cur_maxi + givnList[i])
        # maxi_so_far stores the maximum of maxi_so_far and cur_maxi.
        maxi_so_far = max(maxi_so_far, cur_maxi)
    # return the maxi_so_far
    return maxi_so_far


# Give the array/list as static input and store it in a variable.
givnList = [-3, 4, 1, 2, -1, -4, 3]
# Calculate the length of the given list
# using the len() function and store it in a variable.
listleng = len(givnList)
# Pass the given list and length of the given
# list as an arguments to the findKadane function which implements the kadane's algorithm.
resltsum = findKadane(givnList, listleng)
# Print the maximum sum.
print('The maximum subarray sum of the given list', givnList, ':')
print(resltsum)

Output:

The maximum subarray sum of the given list [-3, 4, 1, 2, -1, -4, 3] :
7

Here it takes O(n) Time Complexity as we traversed only once in the given list. So it is the best and efficient way to find the maximum sum of a subarray in the given list.

3)Implementation(User Input)

Approach:

  • Give the array/list as user input using list(),map(),split() and input() functions.
  • Here the given numbers will get divided by space using the split() function.
  • The string numbers get converted to an integer using map and int functions.
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Pass the given list and length of the given list as an argument to the findKadane function which implements the kadane’s algorithm.
  • It returns the maximum subarray sum for the given list.
  • Print the maximum sum.
  • The Exit of the Program

Below is the implementation:

def findKadane(givnList, listleng):
    # Set both of the variablesto the value at the first index, i.e., givnList[0].
    cur_maxi = givnList[0]
    maxi_so_far = givnList[0]

    for i in range(1, listleng):
      # Store the maximum of givnList[i] and cur_maxi + givnList[i]
      # in the cur_maxi for the following index i.
        cur_maxi = max(givnList[i], cur_maxi + givnList[i])
        # maxi_so_far stores the maximum of maxi_so_far and cur_maxi.
        maxi_so_far = max(maxi_so_far, cur_maxi)
    # return the maxi_so_far
    return maxi_so_far


# Give the array/list as user input using list(),map(),split() and input() functions.
# Here the given numbers will get divided by space using the split() function.
# The string numbers get converted to integer using map and int functions.
givnList = list(
    map(int, input('Enter some random list numbers separated by spaces = ').split()))
# Calculate the length of the given list
# using the len() function and store it in a variable.
listleng = len(givnList)
# Pass the given list and length of the given
# list as an arguments to the findKadane function which implements the kadane's algorithm.
resltsum = findKadane(givnList, listleng)
# Print the maximum sum.
print('The maximum subarray sum of the given list', givnList, ':')
print(resltsum)

Output:

Enter some random list numbers separated by spaces = 2 -1 4 9 -3 -2 10 11 -9 23 -3
The maximum subarray sum of the given list [2, -1, 46, 9, -3, -2, 10, 11, -9, 23, -3] :
86

Time Complexity :O(n)

Related Programs:

Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm Read More »

Python Program to Remove a String from a List of Strings

Python Program to Remove a String from a List of Strings

Given a list of strings and another string the task is to remove the given string from the given list of strings.

Examples:

Example1:

Input:

Given list of strings =['hello', 'this', 'is', 'btechgeeks', 'python', 'coding', 'platform']
Given string ='python'

Output:

The given list of strings before removing the string [ python ] is ['hello', 'this', 'is', 'btechgeeks', 'python', 'coding',
 'platform']
The given list of strings after removing the string [ python ] is ['hello', 'this', 'is', 'btechgeeks', 'coding', 'platform']

Example2:

Input:

Given list of strings =['hello', 'food', 'morning', 'this', 'is', 'btechgeeks', 'online', 'coding', 'platform', 
                                    'for', 'geeks', 'online']
Given string ='geeks'

Output:

The given list of strings before removing the string [ geeks ] is ['hello', 'food', 'morning', 'this', 'is', 'btechgeeks', 
                                                                                                      'online', 'coding', 'platform', 'for', 'geeks', 'online']
The given list of strings after removing the string [ geeks ] is ['hello', 'food', 'morning', 'this', 'is', 'btechgeeks',
                                                                                                  'online', 'coding', 'platform', 'for', 'online']

Program to Remove a String from a List of Strings in Python

Below are the ways to remove the given string from the given list of strings.

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Method #1: Using List Comprehension (Static Input)

Approach:

  • Give the list of strings as static input and store it in a variable.
  • Give the string as static input and store it in another variable.
  • Remove the given strings from the list of strings using List Comprehension.
  • Print the modified list of strings.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as static input and store it in a variable.
gvnstrnlists = ['hello', 'this', 'is',
                'btechgeeks', 'python', 'coding', 'platform']
# Give the string as static input and store it in another variable.
gvnstrng = "python"
print(
    'The given list of strings before removing the string [', gvnstrng, '] is', gvnstrnlists)

# Remove the given strings from the list of strings using List Comprehension.
modilststrngs = [elemen for elemen in gvnstrnlists if elemen != gvnstrng]
# Print the modified list of strings.
print(
    'The given list of strings after removing the string [', gvnstrng, '] is', modilststrngs)

Output:

The given list of strings before removing the string [ python ] is ['hello', 'this', 'is', 'btechgeeks', 'python', 'coding',
 'platform']
The given list of strings after removing the string [ python ] is ['hello', 'this', 'is', 'btechgeeks', 'coding', 'platform']

Method #2: Using List Comprehension (User Input)

Approach:

  • Give the list of strings as user input using list(), split(), and input() functions and store it in a variable.
  • Give the string as user input using input() and store it in another variable.
  • Remove the given strings from the list of strings using List Comprehension.
  • Print the modified list of strings.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as user input using list(), split(),
# and input() functions and store it in a variable.
gvnstrnlists = list(input('Enter some random list of strings = ').split())
# Give the string as user input using input() and store it in another variable.
gvnstrng = input('enter some random string which you want to remove = ')
print(
    'The given list of strings before removing the string [', gvnstrng, '] is', gvnstrnlists)

# Remove the given strings from the list of strings using List Comprehension.
modilststrngs = [elemen for elemen in gvnstrnlists if elemen != gvnstrng]
# Print the modified list of strings.
print(
    'The given list of strings after removing the string [', gvnstrng, '] is', modilststrngs)

Output:

Enter some random list of strings = good morning this is btechgeeks python
enter some random string which you want to remove = this
The given list of strings before removing the string [ this ] is ['good', 'morning', 'this', 'is', 'btechgeeks', 'python']
The given list of strings after removing the string [ this ] is ['good', 'morning', 'is', 'btechgeeks', 'python']

Method #3: Using remove() function (Static Input)

Approach:

  • Give the list of strings as static input and store it in a variable.
  • Give the string as static input and store it in another variable.
  • Loop through the list of strings using For loop.
  • Check if the element is equal to the given string using the If statement.
  • If it is true then remove the element from the given list of strings using the remove() function.
  • Print the modified list of strings.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as static input and store it in a variable.
gvnstrnlists = ['hello', 'this', 'is',
                'btechgeeks', 'python', 'coding', 'platform']
# Give the string as static input and store it in another variable.
gvnstrng = "python"
print(
    'The given list of strings before removing the string [', gvnstrng, '] is', gvnstrnlists)
# Loop through the list of strings using For loop.
for strngele in gvnstrnlists:
    # Check if the element is equal to the given string using the If statement.
    if(strngele == gvnstrng):
        # If it is true then remove the element from the given list
        # of strings using the remove() function.
        gvnstrnlists.remove(strngele)
# Remove the given strings from the list of strings using List Comprehension.
modilststrngs = [elemen for elemen in gvnstrnlists if elemen != gvnstrng]
# Print the modified list of strings.
print(
    'The given list of strings after removing the string [', gvnstrng, '] is', modilststrngs)

Output:

The given list of strings before removing the string [ python ] is ['hello', 'this', 'is', 'btechgeeks', 'python', 'coding', 'platform']
The given list of strings after removing the string [ python ] is ['hello', 'this', 'is', 'btechgeeks', 'coding', 'platform']

Method #4: Using remove() function (User Input)

Approach:

  • Give the list of strings as user input using list(), split(), and input() functions and store it in a variable.
  • Give the string as user input using input() and store it in another variable.
  • Loop through the list of strings using For loop.
  • Check if the element is equal to the given string using the If statement.
  • If it is true then remove the element from the given list of strings using the remove() function.
  • Print the modified list of strings.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as user input using list(), split(),
# and input() functions and store it in a variable.
gvnstrnlists = list(input('Enter some random list of strings = ').split())
# Give the string as user input using input() and store it in another variable.
gvnstrng = input('enter some random string which you want to remove = ')
print(
    'The given list of strings before removing the string [', gvnstrng, '] is', gvnstrnlists)
# Loop through the list of strings using For loop.
for strngele in gvnstrnlists:
    # Check if the element is equal to the given string using the If statement.
    if(strngele == gvnstrng):
        # If it is true then remove the element from the given list
        # of strings using the remove() function.
        gvnstrnlists.remove(strngele)
# Remove the given strings from the list of strings using List Comprehension.
modilststrngs = [elemen for elemen in gvnstrnlists if elemen != gvnstrng]
# Print the modified list of strings.
print(
    'The given list of strings after removing the string [', gvnstrng, '] is', modilststrngs)

Output:

Enter some random list of strings = hello food morning this is btechgeeks online coding platform
 for geeks online
enter some random string which you want to remove = geeks
The given list of strings before removing the string [ geeks ] is ['hello', 'food', 'morning', 'this', 'is', 
'btechgeeks', 'online', 'coding', 'platform', 'for', 'geeks', 'online']
The given list of strings after removing the string [ geeks ] is ['hello', 'food', 'morning', 'this', 'is',
 'btechgeeks', 'online', 'coding', 'platform', 'for', 'online']

Related Programs:

Python Program to Remove a String from a List of Strings Read More »

Python Program for Printing Odd and Even Letters of a String

Python Program for Printing Odd and Even Letters of a String

Strings in Python:

String in Python. The string is an immutable sequence data type in Python. It is a string of Unicode letters surrounded by single, double, or triple quotations… This is the second string in the Multi-line format. If a string literal must embed double quotations as part of a string, it must be enclosed in single quotes.

Given the string, the task is to print even and odd index characters of the given string in Python.

Examples:

Example1:

Input:

The given string = BtechGeeks

Output:

The odd characters in given string =  Behek
The even characters in given string = tcGes

Example2:

Input:

The given string = uploadbutton

Output:

The odd characters in given string = ulabto
The even characters in given string = podutn

Python Program for Printing Odd and Even Letters of a String

Below are the ways to write a Python Program to print Odd and Even Letters of the given String.

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1: Using For Loop and String Concatenation (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take two empty strings(say oddChars and evenChars) and initialize them with a null string using “”.
  • Calculate the length of the string using the len() function and store it in a variable.
  • Loop till the length of the string using For loop.
  • Check if the iterator value is divisible by 2 or not using the If statement.
  • If it is true then concatenate the string iterator value to the oddChars string.
  • Else concatenate the string iterator value to the evenChars string.
  • Print the oddChars string.
  • Print the evenChars string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
givenstring = 'BtechGeeks'
# Take two empty strings(say oddChars and evenChars)
# and initialize them with a null string using "".
evenChars = ""
oddChars = ""
# Calculate the length of the string using the len() function and store it in a variable.
strnglen = len(givenstring)
# Loop till the length of the string using For loop.
for itrvalue in range(strnglen):
    # Check if the iterator value is divisible by 2 or not using the If statement.
    #
    if itrvalue % 2 == 0:
        # If it is true then concatenate the string iterator value to the oddChars string
        oddChars = oddChars + givenstring[itrvalue]
    else:
        # Else concatenate the string iterator value to the evenChars string.
        evenChars = evenChars + givenstring[itrvalue]
print('The given string = ', givenstring)
# Print the oddChars string.
print('The odd characters in given string = ', oddChars)
# Print the evenChars string.
print('The even characters in given string =', evenChars)

Output:

The given string =  BtechGeeks
The odd characters in given string =  Behek
The even characters in given string = tcGes

Method #2: Using For Loop and String Concatenation (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take two empty strings(say oddChars and evenChars) and initialize them with a null string using “”.
  • Calculate the length of the string using the len() function and store it in a variable.
  • Loop till the length of the string using For loop.
  • Check if the iterator value is divisible by 2 or not using the If statement.
  • If it is true then concatenate the string iterator value to the oddChars string.
  • Else concatenate the string iterator value to the evenChars string.
  • Print the oddChars string.
  • Print the evenChars string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
givenstring = input('Enter some random string = ')
# Take two empty strings(say oddChars and evenChars)
# and initialize them with a null string using "".
evenChars = ""
oddChars = ""
# Calculate the length of the string using the len() function and store it in a variable.
strnglen = len(givenstring)
# Loop till the length of the string using For loop.
for itrvalue in range(strnglen):
    # Check if the iterator value is divisible by 2 or not using the If statement.
    #
    if itrvalue % 2 == 0:
        # If it is true then concatenate the string iterator value to the oddChars string
        oddChars = oddChars + givenstring[itrvalue]
    else:
        # Else concatenate the string iterator value to the evenChars string.
        evenChars = evenChars + givenstring[itrvalue]
print('The given string = ', givenstring)
# Print the oddChars string.
print('The odd characters in given string = ', oddChars)
# Print the evenChars string.
print('The even characters in given string =', evenChars)

Output:

Enter some random string = uploadbutton
The given string = uploadbutton
The odd characters in given string = ulabto
The even characters in given string = podutn

Related Programs:

Python Program for Printing Odd and Even Letters of a String Read More »

Program to Find majority element (Boyer–Moore Majority Vote Algorithm)

Python Program to Find majority element (Boyer–Moore Majority Vote Algorithm)

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Given a list, the task is to find the majority element of the given list.

Majority Element:

A majority element appears more than n/2 times, where n is the size of the array.

Boyer–Moore Majority Vote Algorithm History and Introduction:

The Boyer–Moore majority vote algorithm uses linear time and constant space to determine the majority of a series of elements. It is named after Robert S. Boyer and J Strother Moore, who published it in 1981, and is an example of a streaming algorithm.

In its most basic version, the algorithm looks for a majority element, which is an element that appears frequently for more than half of the items in the input. A version of the procedure that performs a second pass through the data can be used to confirm that the element found in the first pass is truly a majority.

If no second pass is conducted and there is no majority, the algorithm will not identify that there is no majority. In the absence of a rigorous majority, the returned element can be random; it is not guaranteed to be the most frequently occurring element (the mode of the sequence). A streaming method cannot discover the most frequent element in less than linear space for sequences with a limited number of repetitions.

Program to Find majority element (Boyer–Moore Majority Vote Algorithm)

Below is the full approach for finding the majority element present in the given array using Boyer-Moore Majority Vote Algorithm.

1)Algorithm:

The algorithm takes up O(1) more space and runs in O(N) time. It takes exactly two traverses across the input list. It’s also pretty straightforward to implement, however understanding how it works is a little more difficult.

We generate a single candidate value in the first traversal, which is the majority value if there is one. To confirm, the second pass simply counts the frequency of that value. The first pass is the most interesting.

We require two values in the first pass:

A candidate value, which can be set to any value at first.
A count, which is originally set to 0.
We begin by looking at the count value for each entry in our input list. If the count is equal to zero, the candidate is set to the value at the current element. Then, compare the value of the element to the current candidate value. If they are the same, we add one to the count. If they vary, we reduce the count by one.
If a majority value exists at the end of all inputs, the candidate will be the majority value. A second O(N) traversal can be used to ensure that the candidate is the majority element.

 Initialize an element ele and a counter in = 0

for each element x of the input sequence:
if in = 0, then
assign ele = x and in = 1
else
if ele = x, then assign in = in + 1
else
assign in = in – 1
return ele

2)Implementation(Static Input)

Give the list as static input and store it in a variable.

Pass the given list to the majoElement function which accepts the given list as an argument and implement the Boyer–Moore majority vote algorithm.

It returns the majority element.

Each element of the sequence is processed one at a time by the algorithm. When working with an element x.
If the counter is zero, set the current candidate to x, and the counter to one.
If the counter is not zero, it should be incremented or decremented depending on whether x is a current contender.
If the sequence has a majority at the end of this phase, it will be the element stored by the algorithm. If there is no majority element, the algorithm will fail to detect it and may output the incorrect element. In other words, when the majority element is present in the input, the Boyer–Moore majority vote algorithm delivers proper results.

Below is the implementation:

# Function to find the majority element present in a given list
def majoElement(given_list):
    # majo stores the majority element (if present in the given list)
    majo = -1
    # initializing counter index with 0
    ind = 0
    # do for each element `A[j]` in the list
    for j in range(len(given_list)):
        # check if the counter index is zero or not.
        if ind == 0:
            # set the current candidate of the given list to givenlist[j]
            majo = given_list[j]
            # change the counter index to 1.
            ind = 1
        # Otherwise, if givenlist[j] is a current candidate, increment the counter.
        elif majo == given_list[j]:
            ind = ind + 1
        # Otherwise, if givenlist[j] is a current candidate, decrement the counter.
        else:
            ind = ind - 1
    # return the majority element
    return majo


# Driver Code
# Give the list as static input and store it in a variable.
given_list = [4, 11, 13, 9, 11, 11, 11, 3, 15, 28, 11, 11, 11, 11]
# Pass the given list to the majoElement function which accepts
# the given list as an argument
# and implement the Boyer–Moore majority vote algorithm.

print("The majority element present in the givenlist",
      given_list, '=', majoElement(given_list))

Output:

The majority element present in the givenlist [4, 11, 13, 9, 11, 11, 11, 3, 15, 28, 11, 11, 11, 11] = 11

3)Implementation(User Input)

i)Integer List

Give the Integer list as user input using map(), int, split(), and list() functions.

store it in a variable.

Pass the given list to the majoElement function which accepts the given list as an argument and implement the Boyer–Moore majority vote algorithm.

It returns the majority element.

Each element of the sequence is processed one at a time by the algorithm. When working with an element x.
If the counter is zero, set the current candidate to x, and the counter to one.
If the counter is not zero, it should be incremented or decremented depending on whether x is a current contender.
If the sequence has a majority at the end of this phase, it will be the element stored by the algorithm. If there is no majority element, the algorithm will fail to detect it and may output the incorrect element. In other words, when the majority element is present in the input, the Boyer–Moore majority vote algorithm delivers proper results.

Below is the implementation:

# Function to find the majority element present in a given list
def majoElement(given_list):
    # majo stores the majority element (if present in the given list)
    majo = -1
    # initializing counter index with 0
    ind = 0
    # do for each element `A[j]` in the list
    for j in range(len(given_list)):
        # check if the counter index is zero or not.
        if ind == 0:
            # set the current candidate of the given list to givenlist[j]
            majo = given_list[j]
            # change the counter index to 1.
            ind = 1
        # Otherwise, if givenlist[j] is a current candidate, increment the counter.
        elif majo == given_list[j]:
            ind = ind + 1
        # Otherwise, if givenlist[j] is a current candidate, decrement the counter.
        else:
            ind = ind - 1
    # return the majority element
    return majo


# Driver Code
# Give the list as user input using map(), int, split(), and list() functions.

# store it in a variable.
given_list = list(map(int,
    input('Enter some random elements of the given list separated by spaces = ').split()))
# Pass the given list to the majoElement function which accepts
# the given list as an argument
# and implement the Boyer–Moore majority vote algorithm.

print("The majority element present in the givenlist",
      given_list, '=', majoElement(given_list))

Output:

Enter some random elements of the given list separated by spaces = 8 12 45 96 3 7 7 1 5 7 7 7 5
The majority element present in the givenlist [8, 12, 45, 96, 3, 7, 7, 1, 5, 7, 7, 7, 5] = 7

ii)String List

Give the string list as user input using split(), and list() functions.

store it in a variable.

Below is the implementation:

# Function to find the majority element present in a given list
def majoElement(given_list):
    # majo stores the majority element (if present in the given list)
    majo = -1
    # initializing counter index with 0
    ind = 0
    # do for each element `A[j]` in the list
    for j in range(len(given_list)):
        # check if the counter index is zero or not.
        if ind == 0:
            # set the current candidate of the given list to givenlist[j]
            majo = given_list[j]
            # change the counter index to 1.
            ind = 1
        # Otherwise, if givenlist[j] is a current candidate, increment the counter.
        elif majo == given_list[j]:
            ind = ind + 1
        # Otherwise, if givenlist[j] is a current candidate, decrement the counter.
        else:
            ind = ind - 1
    # return the majority element
    return majo


# Driver Code
# Give the string list as user input using split(), and list() functions.

# store it in a variable.
given_list = list(input('Enter some random elements of the given list separated by spaces = ').split())
# Pass the given list to the majoElement function which accepts
# the given list as an argument
# and implement the Boyer–Moore majority vote algorithm.

print("The majority element present in the givenlist",
      given_list, '=', majoElement(given_list))

Output:

Enter some random elements of the given list separated by spaces = hello this is btechgeeks is is is si is is
The majority element present in the givenlist ['hello', 'this', 'is', 'btechgeeks', 'is', 'is', 'is', 'si', 'is', 'is'] = is

Related Programs:

Python Program to Find majority element (Boyer–Moore Majority Vote Algorithm) Read More »

Program to print a String N Number of times

Python Program to Print a String N Number of Times

Given a string and the number n the task is to print the given string n number of times in Python.

Examples:

Example1:

Input:

Given string = 'BTechgeeks '
Given number of times = 11

Output:

Printing the given string [ BTechgeeks ] 11 number of times :
BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks

Example2:

Input:

Given string = 'aplustopper '
Given number of times = 8

Output:

Printing the given string [ aplustopper ] 8 number of times :
aplustopper aplustopper aplustopper aplustopper aplustopper aplustopper aplustopper aplustopper

Program to Print a String N Number of Times in Python

Below are the ways to print the given string n number of times in Python.

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the number of times the string to be printed as static input and store it in another variable.
  • Loop till a given number of times using the For loop.
  • Inside the For loop print the given string using the print() statement.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'BTechgeeks'
# Give the number of times the string to be printed
# as static input and store it in another variable.
numbtimes = 11
print('Printing the given string [', gvnstrng, ']', numbtimes,'number of times :')
# Loop till a given number of times using the For loop.
for times in range(numbtimes):
    # Inside the For loop print the given string using the print() statement.
    print(gvnstrng, end=' ')

Output:

Printing the given string [ BTechgeeks ] 11 number of times :
BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Give the number of times the string to be printed as user input using the int(input()) function and store it in another variable.
  • Loop till a given number of times using the For loop.
  • Inside the For loop print the given string using the print() statement.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input()
# function and store it in a variable.

gvnstrng = input('Enter some random string to be printed = ')
# Give the number of times the string to be printed as user input using the int(input()) function
# and store it in another variable.
numbtimes = int(
    input('Enter some random number of times the string to be printed = '))
print('Printing the given string [', gvnstrng,
      ']', numbtimes, 'number of times :')
# Loop till a given number of times using the For loop.
for times in range(numbtimes):
    # Inside the For loop print the given string using the print() statement.
    print(gvnstrng, end=' ')

Output:

Enter some random string to be printed = AplusTopper
Enter some random number of times the string to be printed = 8
Printing the given string [ AplusTopper ] 8 number of times :
AplusTopper AplusTopper AplusTopper AplusTopper AplusTopper AplusTopper AplusTopper AplusTopper

Method #3: Using * Operator (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the number of times the string to be printed as static input and store it in another variable.
  • Print the given string given the number of times using the * operator.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'BTechgeeks '
# Give the number of times the string to be printed
# as static input and store it in another variable.
numbtimes = 11
print('Printing the given string [', gvnstrng,
      ']', numbtimes, 'number of times :')
#Print the given string given the number of times using the * operator.
print(gvnstrng*numbtimes)

Output:

Printing the given string [ BTechgeeks  ] 11 number of times :
BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks BTechgeeks

Method #4: Using * Operator (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Give the number of times the string to be printed as user input using the int(input()) function and store it in another variable.
  • Print the given string given the number of times using the * operator.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input()
# function and store it in a variable.

gvnstrng = input('Enter some random string to be printed = ')
# Give the number of times the string to be printed as user input using the int(input()) function
# and store it in another variable.
numbtimes = int(
    input('Enter some random number of times the string to be printed = '))
print('Printing the given string [', gvnstrng,
      ']', numbtimes, 'number of times :')
# Print the given string given the number of times using the * operator.
print(gvnstrng*numbtimes)

Output:

Enter some random string to be printed = aplustopper 
Enter some random number of times the string to be printed = 8
Printing the given string [ aplustopper ] 8 number of times :
aplustopper aplustopper aplustopper aplustopper aplustopper aplustopper aplustopper aplustopper

Related Programs:

Python Program to Print a String N Number of Times Read More »

Program to Print Even Length Words in a String

Python Program to Print Even Length Words in a String

Given multiple strings separated by spaces, the task is to print even-length words in the given string in Python.

Examples:

Example1:

Input:

Given String ='Hello Good morning this is BTechgeeks online programming platform'

Output:

Even length words in the given string [ Hello Good morning this is BTechgeeks online programming platform ] are:
Good
this
is
BTechgeeks
online
platform

Example2:

Input:

Given String='hello this is btechgeeks online coding platform for btech students'

Output:

Even length words in the given string [ hello this is btechgeeks online coding platform for btech students ] are:
this
is
btechgeeks
online
coding
platform
students

Program to Print Even Length Words in a String in Python

Below are the ways to print even-length words in the given string in Python.

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Convert this string into a list of words and split them with spaces using split() and list() functions.
  • Loop in the words list using For loop.
  • Calculate the length of the word using the len() function.
  • Check if the length of the word is even or not using the If conditional Statement.
  • If it is true then print the word.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'Hello Good morning this is BTechgeeks online programming platform'
print('Even length words in the given string [', gvnstrng, '] are:')
# Convert this string into a list of words and
# split them with spaces using split() and list() functions.
strngwordslist = list(gvnstrng.split())
# Loop in the words list using For loop.
for strngword in strngwordslist:
        # Calculate the length of the word using the len() function.
    wordleng = len(strngword)
    # Check if the length of the word is even or not
    # using the If conditional Statement.
    if(wordleng % 2 == 0):
        # If it is true then print the word.
        print(strngword)

Output:

Even length words in the given string [ Hello Good morning this is BTechgeeks online programming platform ] are:
Good
this
is
BTechgeeks
online
platform

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Convert this string into a list of words and split them with spaces using split() and list() functions.
  • Loop in the words list using For loop.
  • Calculate the length of the word using the len() function.
  • Check if the length of the word is even or not using the If conditional Statement.
  • If it is true then print the word.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvnstrng = input('Enter some random string = ')
print('Even length words in the given string [', gvnstrng, '] are:')
# Convert this string into a list of words and
# split them with spaces using split() and list() functions.
strngwordslist = list(gvnstrng.split())
# Loop in the words list using For loop.
for strngword in strngwordslist:
        # Calculate the length of the word using the len() function.
    wordleng = len(strngword)
    # Check if the length of the word is even or not
    # using the If conditional Statement.
    if(wordleng % 2 == 0):
        # If it is true then print the word.
        print(strngword)

Output:

Enter some random string = hello this is btechgeeks online coding platform for btech students
Even length words in the given string [ hello this is btechgeeks online coding platform for btech students ] are:
this
is
btechgeeks
online
coding
platform
students

Related Programs:

Python Program to Print Even Length Words in a String Read More »