Python

Program to Print Nth word in a given String

Python Program to Print Nth word in a given String

In this article, we will look at how to find the Nth word in a given text using Python.
We frequently encounter circumstances in which we do not require the complete string but merely a certain word from it.

Given multiple strings separated by spaces, the task is to print the Nth word in the given string in Python.

Examples:

Example1:

Input:

Given string =Good morning this is btechgeeks platform
Given n=3

Output:

The [ 3 ] th word in the given Good morning this is btechgeeks platform is { this }

Example2:

Input:

Given string =hello thi sis btechgeeks
Given n=4

Output:

The [ 4 ] th word in the given hello thi sis btechgeeks is { btechgeeks }

Program to Print Nth word in a given String in Python

Below are the ways to print the Nth word in the given string in Python.

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Method #1: Using split() Function (Static Input)

Approach:

  • Give the string as static input and store it in the variable.
  • Give the value of n as static input and store it in another variable.
  • Convert this string into a list of words and split them with spaces using split() and list() functions.
  • Print the nth word in the given list by printing the n-1 indexed element in the above list.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in the variable.
gvnwordsstring = 'Good morning this is btechgeeks platform'
# Give the value of n as static input and store it in another variable.
p = 3
# Convert this string into a list of words and
# split them with spaces using split() and list() functions.
stringwordslist = list(gvnwordsstring.split())

# Print the nth word in the given list by printing the n-1 indexed element
# in the above list.
nthword = stringwordslist[p-1]
print('The [', p, '] th word in the given',
      gvnwordsstring, 'is {', nthword, '}')

Output:

The [ 3 ] th word in the given Good morning this is btechgeeks platform is { this }

Method #2: Using split() Function (User Input)

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Give the value of n as user input using the int(input()) function and store it in another variable.
  • Convert this string into a list of words and split them with spaces using split() and list() functions.
  • Print the nth word in the given list by printing the n-1 indexed element in the above list.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in the variable.
gvnwordsstring = input('Enter some random string = ')
# Give the value of n as user input using the int(input())
# function and store it in another variable.
p = int(input('Enter some random value of n ='))
# Convert this string into a list of words and
# split them with spaces using split() and list() functions.
stringwordslist = list(gvnwordsstring.split())

# Print the nth word in the given list by printing the n-1 indexed element
# in the above list.
nthword = stringwordslist[p-1]
print('The [', p, '] th word in the given',
      gvnwordsstring, 'is {', nthword, '}')

Output:

Enter some random string = hello this is btechgeeks
Enter some random value of n =4
The [ 4 ] th word in the given hello thi sis btechgeeks is { btechgeeks }

Related Programs:

Python Program to Print Nth word in a given String Read More »

Program to Create a Class which Performs Basic Calculator Operations

Python Program to Create a Class which Performs Basic Calculator Operations

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Object-Oriented Programming(OOPS):

The task of Object-Oriented Programming (OOP) is to create “objects.” An object is a collection of interconnected variables and functions. These variables are frequently referred to as object attributes, and functions are referred to as object behavior. These objects improve and clarify the program’s structure.

An automobile, for example, can be an item. If we regard the car to be an item, its properties include its color, model, price, brand, and so on. And its behavior/function would be acceleration, deceleration, and gear shift.

Another example: If we consider a dog to be an object, its properties would be its color, breed, name, weight, and so on. And his behavior/function would include things like walking, barking, playing, and so on.

Object-Oriented programming is well-known for implementing real-world elements such as objects, hiding, inheritance, and so on in programming. It facilitates visualization because it is similar to real-world scenarios.

Python has always been an object-oriented language, as have other general-purpose computer languages. It allows us to develop a program using an Object-Oriented methodology. Python makes it easy to create and use classes and objects.

The task is to write a python program using classes that perform simple calculator operations.

Program to Create a Class which Performs Basic Calculator Operations in Python

Below are the steps to implement the simple calculator in python using classes.

It works best when a user enters equations for the machine to solve. We’ll start by creating a code in which the user enters the numbers that they want the computer to use.

We’ll do this by utilizing Python’s built-in input() function, which accepts user-generated keyboard input. Within the parenthesis of the input() function, we can supply a string to prompt the user. A variable will be assigned to the user’s input.

Make the code prompt for two numbers because we want the user to enter two numbers for this application. When requesting input, we should include a space at the end of our string to separate the user’s input from the prompting string.

Approach:

  • Give the two numbers as static input and store them in two variables.
  • Create a class and use a parameterized constructor to initialize its values.
  • Create methods that calculate the results of adding, subtracting, multiplying, and dividing the given two numbers.
  • Create an object to represent the class.
  • Pass the given two numbers to the class as an argument.
  • Using the object, call the appropriate function based on the user’s selection.
  • The final result will be printed using the print() function.
  • The Exit of the program.

Below is the implementation:

# class
class calculator():
  # use a parameterized constructor to initialize its values.
    def __init__(self, number1, number2):
        self.number1 = number1
        self.number2 = number2
 # function which calculates the sum of the given two numbers

    def addNumbers(self):
        return self.number1+self.number2
 # function which calculates the product of the given two numbers

    def mulNumbers(self):
        return self.number1*self.number2
 # function which divides the given two numbers

    def divNumbers(self):
        return self.number1/self.number2
 # function which calculates the difference of the given two numbers

    def subNumbers(self):
        return self.number1-self.number2


# Give the two numbers as static input and store them in two variables.
number1 = 28
number2 = 11
# Create an object to represent the class.
calobj = calculator(number1, number2)
option = 1
# using while loop
while option != 0:
    print("0. For Exit")
    print("1. For Addition of given two numbers", number1, ',', number2)
    print("2. For Subtraction of given two numbers", number1, ',', number2)
    print("3. For Multiplication of given two numbers", number1, ',', number2)
    print("4. For Division of given two numbers", number1, ',', number2)
    option = int(input("Enter the option/choice you want = "))
    if option == 1:
        print("The additon of given numbers", number1,
              ',', number2, '=', calobj.addNumbers())
    elif option == 2:
        print("The difference of given numbers", number1,
              ',', number2, '=', calobj.subNumbers())
    elif option == 3:
        print("The product of given numbers", number1,
              ',', number2, '=', calobj.mulNumbers())
    elif option == 4:
        print("The division of two numbers", number1,
              ',', number2, '=', calobj.divNumbers())
    elif option == 0:
        print("Exit of program")
    else:
        print("Enter the choice again")
    print()

Output:

0. For Exit
1. For Addition of given two numbers 28 , 11
2. For Subtraction of given two numbers 28 , 11
3. For Multiplication of given two numbers 28 , 11
4. For Division of given two numbers 28 , 11
Enter the option/choice you want = 3
The product of given numbers 28 , 11 = 308

0. For Exit
1. For Addition of given two numbers 28 , 11
2. For Subtraction of given two numbers 28 , 11
3. For Multiplication of given two numbers 28 , 11
4. For Division of given two numbers 28 , 11
Enter the option/choice you want = 2
The difference of given numbers 28 , 11 = 17

0. For Exit
1. For Addition of given two numbers 28 , 11
2. For Subtraction of given two numbers 28 , 11
3. For Multiplication of given two numbers 28 , 11
4. For Division of given two numbers 28 , 11
Enter the option/choice you want = 1
The additon of given numbers 28 , 11 = 39

0. For Exit
1. For Addition of given two numbers 28 , 11
2. For Subtraction of given two numbers 28 , 11
3. For Multiplication of given two numbers 28 , 11
4. For Division of given two numbers 28 , 11
Enter the option/choice you want = 4
The division of two numbers 28 , 11 = 2.5454545454545454

0. For Exit
1. For Addition of given two numbers 28 , 11
2. For Subtraction of given two numbers 28 , 11
3. For Multiplication of given two numbers 28 , 11
4. For Division of given two numbers 28 , 11
Enter the option/choice you want = 0
Exit of program

Explanation:

  • The calculator class is created, and the __init__() function is used to initialize the class’s values.
  • There are defined methods for adding, subtracting, multiplying, and dividing two integers and returning their respective outcomes.
  • The menu is printed, and the user makes his or her selection.
  • The two integers from the user-supplied as inputs are used to generate an instance for the class.
  • The object is used to call the appropriate method based on the user’s selection.
  • The loop is terminated when the choice is 0(End of the infinite loop)
  • The final result is printed.

Python Program to Create a Class which Performs Basic Calculator Operations Read More »

Program to Take in a String and Replace Every Blank Space with Hyphen

Python Program to Take in a String and Replace Every Blank Space with Hyphen

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

given_string='btechgeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string = hello this is BtechGeeks

Output:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

Example2:

Input:

given string = files will be upload to a folder you can read those files in the program folder

Output:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

Program to Take in a String and Replace Every Blank Space with Hyphen

Below are the ways to scan the string and replace every blank space with a hyphen in Python.

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Method #1:Using replace function (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Using the replace function replace all blank space with a hyphen by providing blank space as the first argument and hyphen as the second argument in replace function.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'hello this is BtechGeeks'
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

Method #2:Using replace function (User Input)

Approach:

  • Give the string as user input using the int(input()) function and store it in a variable.
  • Using the replace function replace all blank space with a hyphen by providing blank space as the first argument and hyphen as the second argument in replace function.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using int(input()) function and store it in a variable.
given_string = input('Enter some random string = ')
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

The replace() function replaces all instances of ” with ‘-‘.

Python Program to Take in a String and Replace Every Blank Space with Hyphen Read More »

Program to Form a New String where the First Character and the Last Character have been Exchanged

Python Program to Form a New String where the First Character and the Last Character have been Exchanged

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

given_string='btechgeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string =  hello this is btechgeeks

Output:

The original string before modification = hello this is btechgeeks
The new string after modification = sello this is btechgeekh

Example2:

Input:

given string = this is btechgeeks online coding platform for geeks

Output:

Enter some random string = this is btechgeeks online coding platform for geeks
The original string before modification = this is btechgeeks online coding platform for geeks
The new string after modification = shis is btechgeeks online coding platform for geekt

Program to Form a New String where the First Character and the Last Character have been Exchanged

Below are the ways to form a new string in which the first and last characters have been swapped

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

1)Using slicing(static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a function that swaps the first and last character of the string.
  • Pass the given string as an argument to the function.
  • Split the string in the function.
  • The last character is then added to the middle half of the string, which is then added to the first character.
  • The modified string will be returned.
  • Print the modified string
  • The Exit of the program.

Below is the implementation :

# Take a function that swaps the first and last character of the string.
def swapString(given_string):
    # Split the string in the function.
    # The last character is then added to the middle half of the string,
    # which is then added to the first character.
    modifiedstring = given_string[-1:] + given_string[1:-1] + given_string[:1]
    # The modified string will be returned.
    return modifiedstring


# Give the string as static input and store it in a variable.
given_string = 'hello this is btechgeeks'
# printing the original string before modification
print('The original string before modification =', given_string)
# Pass the given string as an argument to the function.
modified_string = swapString(given_string)
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

The original string before modification = hello this is btechgeeks
The new string after modification = sello this is btechgeekh

Explanation:

  • Give the string as static input and store it in a variable.
  • This string is supplied to a function as an argument.
  • Using string slicing, the string is split into three parts in the function: the last character, the middle part, and the first character.
  • The ‘+’ operator is then used to concatenate these three parts.
  • After that, the modified string is printed.

2)Using slicing(User input)

Approach:

  • Give the string as user input using int(input()) and store it in a variable.
  • Take a function that swaps the first and last character of the string.
  • Pass the given string as an argument to the function.
  • Split the string in the function.
  • The last character is then added to the middle half of the string, which is then added to the first character.
  • The modified string will be returned.
  • Print the modified string
  • The Exit of the program.

Below is the implementation :

# Take a function that swaps the first and last character of the string.
def swapString(given_string):
    # Split the string in the function.
    # The last character is then added to the middle half of the string,
    # which is then added to the first character.
    modifiedstring = given_string[-1:] + given_string[1:-1] + given_string[:1]
    # The modified string will be returned.
    return modifiedstring


# Give the string as user input using int(input()) and store it in a variable.
given_string = input('Enter some random string = ')
# printing the original string before modification
print('The original string before modification =', given_string)
# Pass the given string as an argument to the function.
modified_string = swapString(given_string)
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

Enter some random string = this is btechgeeks online coding platform for geeks
The original string before modification = this is btechgeeks online coding platform for geeks
The new string after modification = shis is btechgeeks online coding platform for geekt

Related Programs:

Python Program to Form a New String where the First Character and the Last Character have been Exchanged Read More »

Program to Calculate the Number of Words and the Number of Characters Present in a String

Python Program to Calculate the Number of Words and the Number of Characters Present in a String

Strings in Python:

In Python, a string may be a sequence of characters. It is an information type that has been derived. Strings are unchangeable. This means that when they have been defined, they can not be modified. Many Python functions change strings, like replace(), join(), and split(). They do not, however, alter the original string. They make a duplicate of a string, alter it, then return it to the caller.

Given a string, the task is to count the words and the total number of characters in the given string in Python.

Examples:

Example1:

Input:

given string ='Hello this is btechgeeks'

Output:

Total characters present in given string { Hello this is btechgeeks } = 24
Total words present in given string { Hello this is btechgeeks } = 4

Example2:

Input:

given string ='hello this is btechgeeks online platform for coding students'

Output:

Total characters present in given string { hello this is btechgeeks online platform for coding students } = 61
Total words present in given string { hello this is btechgeeks online platform for coding students } = 9

Program to Calculate the Number of Words and the Number of Characters Present in a String

There are several ways to count the total number of words and characters in the given string in python some of them are:

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 Count Variable(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable to say stringwords that stores the total words in the given string.
  • Initialize the stringwords to 1.
  • Take a variable to say stringchars that store the total characters in the given string.
  • Initialize the stringchars to 0.
  • To Traverse, the characters in the string, use a for loop and increment the stringchars variable each time by 1.
  • If a space character is encountered then increment the stringwords by 1.
  • Print the total number of characters and words in the string i.e stringchars and stringwords.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'Hello this is btechgeeks'
# Take a variable to say stringchars that store the total characters in the given string.
# Initialize the stringchars to 0.
stringchars = 0
# Take a variable to say stringwords that stores the total words in the given string.
# Initialize the stringwords to 1.
stringwords = 1
# To traverse the characters in the string, use a For loop.
for charact in given_string:
   # If a space character is encountered then increment the stringwords by 1.
    if(charact == ' '):
        stringwords = stringwords+1
     # increment the stringchars variable each time by 1.
    stringchars = stringchars+1
# Print the total words and character present in the given string
print('Total characters present in given string {', given_string, '} =', stringchars)
print('Total words present in given string {', given_string, '} =', stringwords)

Output:

Total characters present in given string { Hello this is btechgeeks } = 24
Total words present in given string { Hello this is btechgeeks } = 4

Explanation:

  • A string must be entered by the user as static input and saved in a variable.
  • 2. The character count variable is set to zero, and the word count variable is set to one (to account for the first word).
  •  The for loop is used to go over the characters in the string.
  • The character count is increased each time a character appears, whereas the word count is increased only when space appears.
  •  The total number of characters and words in the string is printed.

Method #2:Using Count Variable(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable to say stringwords that stores the total words in the given string.
  • Initialize the stringwords to 1.
  • Take a variable to say stringchars that store the total characters in the given string.
  • Initialize the stringchars to 0.
  • To Traverse, the characters in the string, use a for loop and increment the stringchars variable each time by 1.
  • If a space character is encountered then increment the stringwords by 1.
  • Print the total number of characters and words in the string i.e stringchars and stringwords.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using input() function and store it in a variable.
given_string = input('Enter some random string =')
# Take a variable to say stringchars that store the total characters in the given string.
# Initialize the stringchars to 0.
stringchars = 0
# Take a variable to say stringwords that stores the total words in the given string.
# Initialize the stringwords to 1.
stringwords = 1
# To traverse the characters in the string, use a For loop.
for charact in given_string:
   # If a space character is encountered then increment the stringwords by 1.
    if(charact == ' '):
        stringwords = stringwords+1
     # increment the stringchars variable each time by 1.
    stringchars = stringchars+1
# Print the stringLength.
print(
    'Total characters present in given string {', given_string, '} =', stringchars)
print(
    'Total words present in given string {', given_string, '} =', stringwords)

Output:

Enter some random string =hello this is btechgeeks online platform for coding students 
Total characters present in given string { hello this is btechgeeks online platform for coding students } = 61
Total words present in given string { hello this is btechgeeks online platform for coding students } = 9

The output is the total number of characters and words present in the given string.

Method #3:Using split() and len() functions(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the given string into a list of words using list() and split() functions.
  • The length of the list gives the total number of words in the given string and store it in a variable say stringwords.
  • The length of the given string is calculated using the len() function which gives the total number of characters present in the given string.
  • Store this characters count in a variable say stringchars.
  • Print the total number of characters and words in the string i.e stringchars and stringwords.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'hello this is btechgeeks'
# Split the given string into a list of words using list() and split() functions.
listwords = given_string.split()
# The length of the list gives the total number of words in the given string and
# store it in a variable say stringwords.
stringwords = len(listwords)
# The length of the given string is calculated using the len() function which
# gives the total number of characters present in the given string.
stringLeng = len(given_string)
# Store this characters count in a variable say stringchars.
stringchars = stringLeng
#Print the total words and character present in the given string
print('Total characters present in given string {', given_string, '} =', stringchars)
print('Total words present in given string {', given_string, '} =', stringwords)

Output:

Total characters present in given string { hello this is btechgeeks } = 24
Total words present in given string { hello this is btechgeeks } = 4

Method #4:Using split() and len() functions(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Split the given string into a list of words using list() and split() functions.
  • The length of the list gives the total number of words in the given string and store it in a variable say stringwords.
  • The length of the given string is calculated using the len() function which gives the total number of characters present in the given string.
  • Store this characters count in a variable say stringchars.
  • Print the total number of characters and words in the string i.e stringchars and stringwords.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using input() function and store it in a variable.
given_string = input('Enter some random string = ')
# Split the given string into a list of words using list() and split() functions.
listwords = given_string.split()
# The length of the list gives the total number of words in the given string and
# store it in a variable say stringwords.
stringwords = len(listwords)
# The length of the given string is calculated using the len() function which
# gives the total number of characters present in the given string.
stringLeng = len(given_string)
# Store this characters count in a variable say stringchars.
stringchars = stringLeng
# Print the total words and character present in the given string
print('Total characters present in given string {', given_string, '} =', stringchars)
print('Total words present in given string {', given_string, '} =', stringwords)

Output:

Enter some random string = hello this is btechgeeks online platform for coding students
Total characters present in given string { hello this is btechgeeks online platform for coding students } = 61
Total words present in given string { hello this is btechgeeks online platform for coding students } = 9

Related Programs:

Python Program to Calculate the Number of Words and the Number of Characters Present in a String Read More »

Python Program to Implement the Latin Alphabet Cipher

Python Program to Implement the Latin Alphabet Cipher

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

We will learn how to use Python to implement the Latin Alphabet Cipher.

The Latin Alphabet Cipher Encryption Technique is one of the quickest and most straightforward methods of encoding data. It’s essentially a replacement cipher method, in which each letter of a given input is replaced by its matching number as represented alphabetically.

Examples:

Example1:

Input:

Given string =Hello this is BTechGeeks

Output:

The encrypted message of the given string{ Hello this is BTechGeeks }is :
8 5 12 12 15  
20 8 9 19  
9 19  
2 20 5 3 8 7 5 5 11 19

Example2:

Input:

Given string = btechgeeks python

Output:

The encrypted message of the given string{ btechgeeks python }is :
2 20 5 3 8 7 5 5 11 19 
16 25 20 8 15 14

Python Program to Implement the Latin Alphabet Cipher in Python

Below are the ways to implement the Latin Alphabet Cipher in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input(which consists of only alphabets and spaces) and store it in a variable
  • Iterate through the characters of the string using For loop.
  • We can calculate the ASCII value of the character using the ord() function.
  • Now, transform each input string character to its ASCII value and subtract it from the ASCII value of alphabet A for uppercase characters and ‘a’ for lowercase ones.
  • The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
  • ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
  • If the character is space then print it(That is printing space character without endl which makes it to print in next line)
  • The Exit of the program.

Below is the implementation:

# Give the string as static input(which consists of only alphabets and spaces) and store it in a variable
givenstring = "Hello this is BTechGeeks"
print('The encrypted message of the given string{', givenstring, '}is :')
# Iterate through the characters of the string using For loop.
# We can calculate the ASCII value of the character using the ord() function.
for m in givenstring:
    # Now, transform each input string character to its ASCII value
    # and subtract it from the ASCII
    # value of alphabet A for uppercase characters and 'a' for lowercase ones.
    if (m >= "A" and m <= "Z"):
      # The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
        print(ord(m)-ord("A")+1, end=" ")
    elif (m >= "a" and m <= 'z'):
        # ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
        print(ord(m)-ord("a")+1, end=" ")
    # If the character is space then print it(That is printing
    # space character without endl which makes it to print in next line)
    if m == (" "):
        print(m)

Output:

The encrypted message of the given string{ Hello this is BTechGeeks }is :
8 5 12 12 15  
20 8 9 19  
9 19  
2 20 5 3 8 7 5 5 11 19

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input(which consists of only alphabets and spaces) using input() and store it in a variable.
  • Iterate through the characters of the string using For loop.
  • We can calculate the ASCII value of the character using the ord() function.
  • Now, transform each input string character to its ASCII value and subtract it from the ASCII value of alphabet A for uppercase characters and ‘a’ for lowercase ones.
  • The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
  • ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
  • If the character is space then print it(That is printing space character without endl which makes it to print in next line)
  • The Exit of the program.

Below is the implementation:

# Give the string as user input(which consists of only alphabets and spaces)
# using input() and store it in a variable.
givenstring = input('Enter some random string = ')
print('The encrypted message of the given string{', givenstring, '}is :')
# Iterate through the characters of the string using For loop.
# We can calculate the ASCII value of the character using the ord() function.
for m in givenstring:
    # Now, transform each input string character to its ASCII value
    # and subtract it from the ASCII
    # value of alphabet A for uppercase characters and 'a' for lowercase ones.
    if (m >= "A" and m <= "Z"):
      # The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
        print(ord(m)-ord("A")+1, end=" ")
    elif (m >= "a" and m <= 'z'):
        # ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
        print(ord(m)-ord("a")+1, end=" ")
    # If the character is space then print it(That is printing
    # space character without endl which makes it to print in next line)
    if m == (" "):
        print(m)

Output:

Enter some random string = btechgeeks python
The encrypted message of the given string{ btechgeeks python }is :
2 20 5 3 8 7 5 5 11 19 
16 25 20 8 15 14

Related Programs:

Python Program to Implement the Latin Alphabet Cipher Read More »

Program to Take in Two Strings and Display the Larger String without Using Built-in Functions

Python Program to Take in Two Strings and Display the Larger String without Using Built-in Functions

Strings in Python:

In Python, a string may be a sequence of characters. It is an information type that has been derived. Strings are unchangeable. This means that when they have been defined, they can not be modified. Many Python functions change strings, like replace(), join(), and split(). They do not, however, alter the original string. They make a duplicate of a string, alter it, then return it to the caller.

Given a string, the task is to scan the given two strings and print the larger string without using built-in functions in python.

Examples:

Example1:

Input:

given first string =btechgeeks

given second string =python

Output:

The string btechgeeks is larger string

Example2:

Input:

given first string =java

given second string =javascript

Output:

The string javascript is larger string

Program to Take in Two Strings and Display the Larger String without Using Built-in Functions in Python

Below is the full approach is to scan the given two strings and print the larger string without using built-in functions in python.

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.

1)Using Count Variable and conditional statements(Static Input)

Approach:

  • Give the two strings as static input and store them in two separate variables.
  • Take a variable to say stringLength1 that stores the length of the given first string.
  • Initialize the stringLength1 to 0.
  • Take a variable to say stringLength2 that stores the length of the given second string.
  • Initialize the stringLength2 to 0.
  • Using for loop to traverse over the elements of the first string.
  • Increment the stringLength1 (Count Variable) by 1.
  • Using for loop to traverse over the elements of the second string.
  • Increment the stringLength2 (Count Variable) by 1.
  • Compare the count variables(stringLength1 ,stringLength2) of both the strings using if conditional statement.
  • If the stringlength1 is greater than stringlength2 then print the first string using the print() function.
  • If the stringlength1 is equal to stringlength2 then print both the strings are equal using the print() function.
  • If the stringlength1 is less than stringlength2 then print the second string using the print() function.
  • The Exit of the Program.

Below is the implementation:

# Give the two strings as static input and store them in two separate variables.
firststrng = 'btechgeeks'
secondstrng = 'python'
# Take a variable to say stringLength1 that stores the length of the given first string.
# Initialize the stringLength1 to 0.
stringLength1 = 0
# Take a variable to say stringLength2 that stores the length of the given second string.
# Initialize the stringLength2 to 0.
stringLength2 = 0
# Using for loop to traverse over the elements of the first string.
for charact in firststrng:
    # Increment the stringLength1 (Count Variable) by 1.
    stringLength1 = stringLength1+1
# Using for loop to traverse over the elements of the second string.
for charact in secondstrng:
    # Increment the stringLength2 (Count Variable) by 1.
    stringLength2 = stringLength2+1
# Compare the count variables(stringLength1 ,stringLength2) of both
# the strings using if conditional statement.
# If the stringlength1 is greater than stringlength2 then
# print the first string using the print() function.
if(stringLength1 > stringLength2):
    print('The string', firststrng, 'is  larger string')
# If the stringlength1 is equal to stringlength2 then
# print both the strings are equal using the print() function.
elif(stringLength1 == stringLength2):
    print('The strings', firststrng, 'and', secondstrng, 'are equal in size')
# If the stringlength1 is less than stringlength2 then
# print the second string using the print() function.
else:
    print('The string', secondstrng, 'is  larger string')

Output:

The string btechgeeks is larger string

2)Using Count Variable and conditional statements(User Input)

Approach:

  • Give the two strings as user input using the input() function and store them in two separate variables.
  • Take a variable to say stringLength1 that stores the length of the given first string.
  • Initialize the stringLength1 to 0.
  • Take a variable to say stringLength2 that stores the length of the given second string.
  • Initialize the stringLength2 to 0.
  • Using for loop to traverse over the elements of the first string.
  • Increment the stringLength1 (Count Variable) by 1.
  • Using for loop to traverse over the elements of the second string.
  • Increment the stringLength2 (Count Variable) by 1.
  • Compare the count variables(stringLength1 ,stringLength2) of both the strings using if conditional statement.
  • If the stringlength1 is greater than stringlength2 then print the first string using the print() function.
  • If the stringlength1 is equal to stringlength2 then print both the strings are equal using the print() function.
  • If the stringlength1 is less than stringlength2 then print the second string using the print() function.
  • The Exit of the Program.

Below is the implementation:

# Give the two strings as user input using the input() function
# and store them in two separate variables.
firststrng = input('Enter some random first string = ')
secondstrng = input('Enter some random second string = ')
# Take a variable to say stringLength1 that stores the length of the given first string.
# Initialize the stringLength1 to 0.
stringLength1 = 0
# Take a variable to say stringLength2 that stores the length of the given second string.
# Initialize the stringLength2 to 0.
stringLength2 = 0
# Using for loop to traverse over the elements of the first string.
for charact in firststrng:
    # Increment the stringLength1 (Count Variable) by 1.
    stringLength1 = stringLength1+1
# Using for loop to traverse over the elements of the second string.
for charact in secondstrng:
    # Increment the stringLength2 (Count Variable) by 1.
    stringLength2 = stringLength2+1
# Compare the count variables(stringLength1 ,stringLength2) of both
# the strings using if conditional statement.
# If the stringlength1 is greater than stringlength2 then
# print the first string using the print() function.
if(stringLength1 > stringLength2):
    print('The string', firststrng, 'is larger string')
# If the stringlength1 is equal to stringlength2 then
# print both the strings are equal using the print() function.
elif(stringLength1 == stringLength2):
    print('The strings', firststrng, 'and', secondstrng, 'are equal in size')
# If the stringlength1 is less than stringlength2 then
# print the second string using the print() function.
else:
    print('The string', secondstrng, 'is larger string')

Output:

Enter some random first string = vikram
Enter some random second string = vishalraj
The string vishalraj is larger string

Explanation:

  • The user must enter two strings and store them in different variables.
  • The count variables are set to zero.
  • To iterate through the characters in the strings, the for loop is utilized.
  • When a character is encountered, the count variables are incremented.
  • After that, the count variables are compared, and the longer string is printed.

Related Programs:

Python Program to Take in Two Strings and Display the Larger String without Using Built-in Functions Read More »

Python Program to Check if a Substring is Present in a Given String

Strings in Python:

“String is a character collection or array”

Well in Python too, for the string data type, we say the same definition. The string is a sequenced character array and is written within single, double, or three quotes. Also, Python does not have the data type character, thus it is used as a string of length 1 if we write ‘V’.

Substring in Python:

A substring in Python is a sequence of characters within another string. It is also known as string slicing in Python.

Given a string and substring, the task is to check whether the given substring exists in the given string or not in Python

Examples:

Example1:

Input:

given string = hello this is BTechgeeks 
given substring = BTechgeeks

Output:

The substring [ BTechgeeks ] is found in [ hello this is BTechgeeks ]

Example2:

Input:

given string = good morning virat
given substring = morning

Output:

The substring [ morning ] is found in [ good morning virat ]

Program to Check if a Substring is Present in a Given String in Python

There are several ways to check if the given substring exists in a given string or not in Python some of them are:

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

Method #1:Using find() function (Static Input)

Approach:

  • Give string and substring as static input and store them in two separate variables.
  • Using the in-built find() method, determine whether the substring exists in the given string.
  • If the find() function returns -1 then the given substring isn’t found in the given string.
  • Else the given substring is found in the given string
  • The Exit of the program.

Below is the implementation:

# Give string and substring as static input and store them in two separate variables
given_strng = 'hello this is BTechgeeks'
# given substring
given_substring = 'BTechgeeks'
# Using the in-built find() method, determine
# whether the substring exists in the given string.
# If the find() function returns -1 then the given substring isn't found in the given string.
if(given_strng.find(given_substring) == -1):
    print('The substring [', given_substring,
          '] is not found in [', given_strng, ']')
else:
    print('The substring [', given_substring,
          '] is found in [', given_strng, ']')

Output:

The substring [ BTechgeeks ] is found in [ hello this is BTechgeeks ]

Method #2:Using find() function (User Input)

Approach:

  • Give string and substring as user input using input() function and store them in two separate variables.
  • Using the in-built find() method, determine whether the substring exists in the given string.
  • If the find() function returns -1 then the given substring isn’t found in the given string.
  • Else the given substring is found in the given string
  • The Exit of the program.

Below is the implementation:

# Give string and substring as user input using input() function
# and store them in two separate variables.
given_strng = input('Enter some random string = ')
# given substring
given_substring = input('Enter some random substring = ')
# Using the in-built find() method, determine
# whether the substring exists in the given string.
# If the find() function returns -1 then the given substring isn't found in the given string.
if(given_strng.find(given_substring) == -1):
    print('The substring [', given_substring,
          '] is not found in [', given_strng, ']')
else:
    print('The substring [', given_substring,
          '] is found in [', given_strng, ']')

Output:

Enter some random string = good morning virat
Enter some random substring = morning
The substring [ morning ] is found in [ good morning virat ]

Explanation:

  • A string and a substring from the user must be entered and stored in separate variables.
  • The in-built method find() is then used to see if the substring is present in the string.
  • The decision is made using an if statement, and the final result is printed.

Method #3:Using in operator (Static Input)

Approach:

  • Give string and substring as static input and store them in two separate variables.
  • Using the in operator, determine whether the substring exists in the given string.
  • If it returns true, then the given substring is found in the given string.
  • Else the given substring isn’t found in the given string
  • The Exit of the program.

Below is the implementation:

# Give string and substring as static input and store them in two separate variables.
given_strng = 'hello this is BTechgeeks'
# given substring
given_substring = 'BTechgeeks'
# Using the in operator, determine whether the substring exists in the given string
# If it returns true, then the given substring is found in the given string.
if given_substring in given_strng:
    print('The substring [', given_substring,
          '] is  found in [', given_strng, ']')
# Else the given substring isn't found in the given string
else:
    print('The substring [', given_substring,
          '] is not found in [', given_strng, ']')

Output:

The substring [ BTechgeeks ] is  found in [ hello this is BTechgeeks ]

Method #4:Using in operator (User Input)

Approach:

  • Give string and substring as user input using input() function and store them in two separate variables.
  • Using the in operator, determine whether the substring exists in the given string.
  • If it returns true, then the given substring is found in the given string.
  • Else the given substring isn’t found in the given string
  • The Exit of the program.

Below is the implementation:

# Give string and substring as user input using input() function
# and store them in two separate variables.
given_strng = input('Enter some random string = ')
# given substring
given_substring = input('Enter some random substring = ')
# Using the in operator, determine whether the substring exists in the given string
# If it returns true, then the given substring is found in the given string.
if given_substring in given_strng:
    print('The substring [', given_substring,
          '] is  found in [', given_strng, ']')
# Else the given substring isn't found in the given string
else:
    print('The substring [', given_substring,
          '] is not found in [', given_strng, ']')

Output:

Enter some random string = this is that
Enter some random substring = are
The substring [ are ] is not found in [ this is that ]

Related Programs:

Python Program to Check if a Substring is Present in a Given String Read More »

Program to Form a New String Made of the First 2 and Last 2 characters From a Given String

Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String

Strings in Python:

“String is a character collection or array”

Well in Python too, for the string data type, we say the same definition. The string is a sequenced character array and is written within single, double, or three quotes. Also, Python does not have the data type character, thus it is used as a string of length 1 if we write ‘r’.

Given a string, the task is to form a new string which is made of the First 2 and Last 2 characters From a Given String in Python.

Examples:

Example1:

Input:

given string =BTechGeeks

Output:

BTks

Example2:

Input:

given string =AplusTopper

Output:

Aper

Program to Form a New String Made of the First 2 and Last 2 characters From a Given String

Below is the full approach to form a new string which is made of the First 2 and Last 2 characters From a Given String in Python.

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.

1)Using indexing, Slicing, and Count Variable(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable to say stringcharacters that stores the total characters in the given string.
  • Initialize the stringcharacters to 0.
  • Traverse through the given string using For loop.
  • Increment the value of stringcharacters by 1.
  • Using String Concatenation and slicing form the new string with which is made of the First 2 and Last 2 characters From a Given String.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_strng = 'BTechGeeks'
# Take a variable to say stringcharacters that stores the total characters in the given string.
# Initialize the stringcharacters to 0.
stringcharacters = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Increment the value of stringcharacters by 1.
    stringcharacters = stringcharacters+1
# Using String Concatenation and slicing form the new string with which is made of the First two
# and Last two characters From a Given String.
resstring = given_strng[0:2]+given_strng[stringcharacters-2:stringcharacters]
# print the result string
print(resstring)

Output:

BTks

2)Using indexing, Slicing, and Count Variable(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable to say stringcharacters that stores the total characters in the given string.
  • Initialize the stringcharacters to 0.
  • Traverse through the given string using For loop.
  • Increment the value of stringcharacters by 1.
  • Using String Concatenation and slicing form the new string with which is made of the First 2 and Last 2 characters From a Given String.
  • Print the modified 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.
given_strng = input('Enter some random string = ')
# Take a variable to say stringcharacters that stores the total characters in the given string.
# Initialize the stringcharacters to 0.
stringcharacters = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Increment the value of stringcharacters by 1.
    stringcharacters = stringcharacters+1
# Using String Concatenation and slicing form the new string with which is made of the First two
# and Last two characters From a Given String.
resstring = given_strng[0:2]+given_strng[stringcharacters-2:stringcharacters]
# print the result string
print(resstring)

Output:

Enter some random string = AplusTopper
Aper

Explanation:

  • A string must be entered by the user and saved in a variable.
  • The count variable is set to zero.
  • The for loop is used to go over the characters in a string.
  • When a character is encountered, the count is increased.
  • String slicing is used to create the new string, and the first and last two characters of the string are concatenated using the ‘+’ operator.
  • The string that has just been formed is printed.

3)Using indexing, Slicing, and len() function(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Calculate the length of the string using the len() function and store it in a variable.
  • Using String Concatenation and slicing form the new string with which is made of the First 2 and Last 2 characters From a Given String.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_strng = 'BTechGeeks'
# Calculate the length of the string using the len() function and store it in a variable.
stringcharacters = len(given_strng)
# Using String Concatenation and slicing form the new string with which is made of the First two
# and Last two characters From a Given String.
resstring = given_strng[0:2]+given_strng[stringcharacters-2:stringcharacters]
# print the result string
print(resstring)

Output:

BTks

Here string concatenation is used to combine the characters using string slicing and length of the string.

4)Using indexing, Slicing, and len() function(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Calculate the length of the string using the len() function and store it in a variable.
  • Using String Concatenation and slicing form the new string with which is made of the First 2 and Last 2 characters From a Given String.
  • Print the modified 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.
given_strng = input('Enter some random string = ')
# Calculate the length of the string using the len() function and store it in a variable.
stringcharacters = len(given_strng)
# Using String Concatenation and slicing form the new string with which is made of the First two
# and Last two characters From a Given String.
resstring = given_strng[0:2]+given_strng[stringcharacters-2:stringcharacters]
# print the result string
print(resstring)

Output:

Enter some random string = AplusTopper
Aper

Here string concatenation is used to combine the characters using string slicing and length of the string.
Related Programs:

Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String Read More »

Program to Remove the Characters of Odd Index Values in a String

Python Program to Remove the Characters of Odd Index Values in a String

Strings in Python:

A string is a series of one or more characters (letters, integers, symbols) that might be constant or variable. Strings, which are made up of Unicode, are immutable sequences, which means they do not change.

Because the text is such a frequent type of data in our daily lives, the string data type is a critical building block of programming.

Given a string, the task is to remove all the characters present at odd indices in the given string in Python

Examples:

Example1:

Input:

given string = HelloThisisBTechgeeks

Output:

The given string before modification =  HelloThisisBTechgeeks
The given string after modification =  HlohssTcges

Example2:

Input:

given string = btechgeeks online coding platform for coding studeents

Output:

Enter the given random string = btechgeeks online coding platform for coding studeents
The given string before modification = btechgeeks online coding platform for coding studeents
The given string after modification = behek niecdn ltomfrcdn tdet

Program to Remove the Characters of Odd Index Values in a String in Python

There are several ways to remove all the characters present at odd indices in the given string in Python some of them are:

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 Modulus operator and String Concatenation(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Create a function say removeOddString that accepts the string as an argument and removes all the characters present at odd indices in the given string.
  • Pass the given string as an argument to the removeOddString function.
  • In the function take an empty string say tempstng using ”.
  • Traverse the given string using For loop.
  • Use an if statement and modulus operator to determine whether the string’s index is odd or even.
  • If the index is an even number, append the character to the tempstng using String Concatenation.
  • Return the tempstng.
  • Print the modified string which is returned from the function.
  • The Exit of the program.

Below is the implementation:

# function  that accepts the string as an argument
# and removes all the characters present at odd indices in the given string.


def removeOddString(givenstrng):
    # In the function take an empty string say tempstng using '' .
    tempstng = ""
    # Traverse the given string using For loop.
    for charindex in range(len(givenstrng)):
        # Use an if statement and modulus operator to
        # determine whether the string's index is odd or even.
        if charindex % 2 == 0:
            # If the index is an even number, append the
            # character to the tempstng using String Concatenation.
            tempstng = tempstng + givenstrng[charindex]
    # Return the tempstng.
    return tempstng


# Give the string as static input and store it in a variable.
givenstrng = 'HelloThisisBTechgeeks'
# print the given string without modification'
print('The given string before modification = ', givenstrng)
# Pass the given string as an argument to the removeOddString function.
resstrng = removeOddString(givenstrng)
# print the given string after modification
print('The given string after modification = ', resstrng)

Output:

The given string before modification =  HelloThisisBTechgeeks
The given string after modification =  HlohssTcges

Method #2)Using Modulus operator and String Concatenation(User Input)

Approach:

  • Give the string as the user input with the help of the input() function and store it in a variable.
  • Create a function say removeOddString that accepts the string as an argument and removes all the characters present at odd indices in the given string.
  • Pass the given string as an argument to the removeOddString function.
  • In the function take an empty string say tempstng using ”.
  • Traverse the given string using For loop.
  • Use an if statement and modulus operator to determine whether the string’s index is odd or even.
  • If the index is an even number, append the character to the tempstng using String Concatenation.
  • Return the tempstng.
  • Print the modified string which is returned from the function.
  • The Exit of the program.

Below is the implementation:

# function  that accepts the string as an argument
# and removes all the characters present at odd indices in the given string.


def removeOddString(givenstrng):
    # In the function take an empty string say tempstng using '' .
    tempstng = ""
    # Traverse the given string using For loop.
    for charindex in range(len(givenstrng)):
        # Use an if statement and modulus operator to
        # determine whether the string's index is odd or even.
        if charindex % 2 == 0:
            # If the index is an even number, append the
            # character to the tempstng using String Concatenation.
            tempstng = tempstng + givenstrng[charindex]
    # Return the tempstng.
    return tempstng


# Give the string as the user input with the help of input() function and store it in a variable.
givenstrng = input('Enter the given random string = ')
# print the given string without modification'
print('The given string before modification = ', givenstrng)
# Pass the given string as an argument to the removeOddString function.
resstrng = removeOddString(givenstrng)
# print the given string after modification
print('The given string after modification = ', resstrng)

Output:

Enter the given random string = btechgeeks online coding platform for coding studeents
The given string before modification = btechgeeks online coding platform for coding studeents
The given string after modification = behek niecdn ltomfrcdn tdet

Explanation:

  • A string must be entered by the user and saved in a variable.
  • This string is provided to a function as an argument.
  • A variable is initialized with an empty character in the function.
  • To iterate through the string, a for loop is needed.
  • An if statement determines whether the string’s index is odd or even.
  • If the index is even, the empty character variable is appended to the string, eliminating the character indirectly.
  • Finally, the updated string is printed.

Method #3:Using List Comprehension and Join function(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Create a function say removeOddString that accepts the string as an argument and removes all the characters present at odd indices in the given string.
  • Pass the given string as an argument to the removeOddString function.
  • Convert the given string into a list of characters using the list() function.
  • Using list comprehension with the help of the if and modulus operator eliminates the odd index characters.
  • Join the list into the string using the join() function.
  • Return the modified string.
  • Print the modified string which is returned from the function.
  • The Exit of the program.

Below is the implementation:

# function  that accepts the string as an argument
# and removes all the characters present at odd indices in the given string.


def removeOddString(givenstrng):
    # Convert the given string into a list of characters using the list() function.
    liststrng = list(givenstrng)
    # Using list comprehension with the help of the if and modulus operator eliminates the odd index characters.
    liststrng = [givenstrng[inde]
                 for inde in range(len(givenstrng)) if inde % 2 == 0]
    # Join the list into the string using the join() ffunction.
    tempstng = ''.join(liststrng)
    # Return the tempstng.
    return tempstng


# Give the string as static input and store it in a variable.
givenstrng = 'Hello this is BTechGeeks online coding platform for coding students'
# print the given string without modification'
print('The given string before modification = ', givenstrng)
# Pass the given string as an argument to the removeOddString function.
resstrng = removeOddString(givenstrng)
# print the given string after modification
print('The given string after modification = ', resstrng)

Output:

The given string before modification =  Hello this is BTechGeeks online coding platform for coding students
The given string after modification =  Hloti sBehek niecdn ltomfrcdn tdns

Method #4:Using List Comprehension and Join function(User Input)

Approach:

  • Give the string as the user input with the help of the input() function and store it in a variable.
  • Create a function say removeOddString that accepts the string as an argument and removes all the characters present at odd indices in the given string.
  • Pass the given string as an argument to the removeOddString function.
  • Convert the given string into a list of characters using the list() function.
  • Using list comprehension with the help of the if and modulus operator eliminates the odd index characters.
  • Join the list into the string using the join() function.
  • Return the modified string.
  • Print the modified string which is returned from the function.
  • The Exit of the program.

Below is the implementation:

# function  that accepts the string as an argument
# and removes all the characters present at odd indices in the given string.


def removeOddString(givenstrng):
    # Convert the given string into a list of characters using the list() function.
    liststrng = list(givenstrng)
    # Using list comprehension with the help of the if and modulus operator eliminates the odd index characters.
    liststrng = [givenstrng[inde]
                 for inde in range(len(givenstrng)) if inde % 2 == 0]
    # Join the list into the string using the join() ffunction.
    tempstng = ''.join(liststrng)
    # Return the tempstng.
    return tempstng


# Give the string as the user input with the help of input() function and store it in a variable.
givenstrng = input('Enter the given random string = ')
# print the given string without modification'
print('The given string before modification = ', givenstrng)
# Pass the given string as an argument to the removeOddString function.
resstrng = removeOddString(givenstrng)
# print the given string after modification
print('The given string after modification = ', resstrng)

Output:

Enter the given random string = good morning this is btechgeeks
The given string before modification = good morning this is btechgeeks
The given string after modification = go onn hsi tcges

Related Programs:

Python Program to Remove the Characters of Odd Index Values in a String Read More »