Author name: Vikram Chiluka

Replace Character in String by Index Position

Python: Replace Character in String by Index Position | How do you Replace Character at Index in String Python?

In this article, we have discussed how to replace a character in a string by Index Position. For your reference, we have outlined several methods for replacing characters in the string like slicing, replacing characters at multiple indexes, replacing multiple characters at multiple indexes, etc. Check out Sample Programs for Replacing Characters on String by Index Position for a better understanding of how to write code.

String – Definition

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Examples:

Input:

string="Hello this is BTechGeeks" index=4 character='w'

Output:

Hellw this is BTechGeeks

Replace Character In String by Index Position in Python

There are several ways to replace characters in a string by index some of them are:

Method #1:Using Slicing to replace the character at index

Split a string in three sections in order to replace an index-position n character: characters before nth character, nth character and nth characters. Then add a new string and use the replacement character instead of using the nth character.

Below is the implementation:

Python Program using Slicing to Replace a Character in String by Index Position

# given string
string = "Hello this is BTechGeeks"
# given index
index = 4
# given character
character = 'w'
# using slicing to replace it
string = string[:index]+character+string[index+1:]
# print the string
print(string)

Output:

Hellw this is BTechGeeks

Method #2:Replace characters at multiple indexes

We have few index positions, and at these Index positions, we want to replace all characters. To achieve this, all index positions in the list will be iterated. And substitute the character on that index by cutting the string for each index

Below is the implementation:

Python Program to Replace characters at multiple indexes

# function which replaces the string
def replaceString(string, index, character):
    # replacing the string
    newString = string[:index]+character+string[index+1:]
    # return the string
    return newString


# given string
string = "Hello this is BTechGeeks"
# given index list
indexlist = [1, 4, 8]
# given character
character = 'w'
# Traversing the indexlist
for index in indexlist:
    string = replaceString(string, index, character)
# print the string
print(string)

Output:

Hwllw thws is BTechGeeks

Method #3: Replace multiple characters at multiple indexes

In the example above, we replace all characters with the same substitute characters in given positions. But we may want to have different replacement characters in certain scenarios.
If we have a dictionary with key-value pairs that contain the index positions and substitute characters. We want to substitute the corresponding replacement character in all characters at those index positions. This will be done through all of the dictionary’s key-value pairs. And replace each key with the character in the value field at that index position.

Below is the implementation:

# function which replaces the string
def replaceString(string, index, character):
    # replacing the string
    newString = string[:index]+character+string[index+1:]
    # return the string
    return newString


# given string
string = "Hello this is BTechGeeks"
# given index and characters
charsdict = {1: 'p', 4: 'q', 8: 's'}
# Traversing the charsdict
for index in charsdict:
    string = replaceString(string, index, charsdict[index])
# print the string
print(string)

Output:

Hpllq thss is BTechGeeks

Related Programs:

Python: Replace Character in String by Index Position | How do you Replace Character at Index in String Python? Read More »

Python Program To Remove all Duplicates Words from a Sentence

Counter() function in Python:

Python Counter is a container that keeps track of the count of each element in the container. The counter class is a subclass of the dictionary class.

The counter class is a subclass of the dictionary class. You can count the key-value pairs in an object, also known as a hash table object, using the Python Counter tool.

split() Method:

To extract the words from the string, we used the split() method with space as the separator, which returns a list of the words in the string.

key() method :

The key() method will be used to retrieve the keys of a dictionary. It returns all of the keys in a dictionary.

Given a string/sentence and the task is to remove all the duplicate words from a given sentence.

Examples:

Example1:

Input:

Given String =  'good morning btechgeeks good morning hello all all'

Output:

The given sentence after the removal of all duplicate words :
good morning btechgeeks hello all

Example2:

Input:

Given String = ' health is is wealth so protect it so so'

Output:

The given sentence after the removal of all duplicate words :
health is wealth so protect it

Program To Remove all Duplicates Words from a Sentence

Below are the ways to remove all the duplicate words from a given sentence.

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

Approach:

  • Import the Counter() function from the collections module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Split the given string into a list of words using the split() function and store it in another variable.
  • Apply Counter() function on the above-obtained list of words and store it in another variable.
  • Join all the keys of the above-obtained dictionary using the join() function and store it in another variable.
  • Print the given sentence after the removal of all duplicate words.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from the collections module using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable.
gvn_str = 'good morning btechgeeks good morning hello all all'
# Split the given string into a list of words using the split() function and
# store it in another variable.
splt_str = gvn_str.split(" ")
# Apply Counter() function on the above-obtained list of words and store it
# in another variable.
dictinry = Counter(splt_str)
# Join all the keys of the above-obtained dictionary using the join() function
# and store it in another variable.
reslt = " ".join(dictinry.keys())
# Print the given sentence after the removal of all duplicate words.
print("The given sentence after the removal of all duplicate words :")
print(reslt)

Output:

The given sentence after the removal of all duplicate words :
good morning btechgeeks hello all

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

Approach:

  • Import the Counter() function from the collections module using the import keyword.
  • 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 the split() function and store it in another variable.
  • Apply Counter() function on the above-obtained list of words and store it in another variable.
  • Join all the keys of the above-obtained dictionary using the join() function and store it in another variable.
  • Print the given sentence after the removal of all duplicate words.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from the collections module using the import keyword.
from collections import Counter
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string : ")
# Split the given string into a list of words using the split() function and
# store it in another variable.
splt_str = gvn_str.split(" ")
# Apply Counter() function on the above-obtained list of words and store it
# in another variable.
dictinry = Counter(splt_str)
# Join all the keys of the above-obtained dictionary using the join() function
# and store it in another variable.
reslt = " ".join(dictinry.keys())
# Print the given sentence after the removal of all duplicate words.
print("The given sentence after the removal of all duplicate words :")
print(reslt)

Output:

Enter some random string : health is is wealth so protect it so so
The given sentence after the removal of all duplicate words :
health is wealth so protect it

 

 

Python Program To Remove all Duplicates Words from a Sentence Read More »

Python Program to Remove the Last Word from String

Given a string and the task is to remove the last word from the given string.

split() method :

Splitting a string into a list is accomplished by the split() method.

join() function:

The join() method is a string method that returns a string containing the elements of a sequence that have been joined by a string separator.

Examples:

Example1:

Input:

Given string = "good morning this is btechgeeks hello all"

Output:

The given string after removal of last word from a string:
good morning this is btechgeeks hello

Example2:

Input:

Given string = "Hello this is btechgeeks "

Output:

The given string after removal of last word from a string: Hello this is

Program to Remove the Last Word from String

Below are the ways to remove the last word from the given string.

Method #1: Using Slicing (Static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the given string separated by spaces using the split function() and store it in another variable.
  • Remove the last word from a given string using the slicing and store it in another variable.
  • Convert the above-obtained list to string using the join() function and store it in a variable.
  • Print the given string after removal of the last word from a string.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "Hello this is btechgeeks "
# Split the given string separated by spaces using the split function()
# and store it in another variable.
splt_str = gvn_str.split()
# Remove the last word from a string using the slicing and store it in another variable.
rmove_lst_wrd = splt_str[:-1]
# Convert the above-obtained list to string using the join() function and
# store it in a variable.
fnl_str = ' '.join(rmove_lst_wrd)
print("The given string after removal of last word from a string:")
# Print the given string after removal of the last word from a string.
print(fnl_str)

Output:

The given string after removal of last word from a string:
Hello this is

Method #2: Using Slicing (User input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Split the given string separated by spaces using the split function() and store it in another variable.
  • Remove the last word from a given string using the slicing and store it in another variable.
  • Convert the above-obtained list to string using the join() function and store it in a variable.
  • Print the given string after removal of the last word from a string.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Split the given string separated by spaces using the split function()
# and store it in another variable.
splt_str = gvn_str.split()
# Remove the last word from a string using the slicing and store it in another variable.
rmove_lst_wrd = splt_str[:-1]
# Convert the above-obtained list to string using the join() function and
# store it in a variable.
fnl_str = ' '.join(rmove_lst_wrd)
print("The given string after removal of last word from a string:")
# Print the given string after removal of the last word from a string.
print(fnl_str)

Output:

Enter some random string = good morning this is btechgeeks hello all
The given string after removal of last word from a string:
good morning this is btechgeeks hello

Python Program to Remove the Last Word from String Read More »

Program to Print Items from a List with Specific Length

Python Program to Print Items from a List with Specific Length

In the previous article, we have discussed Python Program to Add Number to each Element in a List
Given a list of a string and some specific length and the task is to print items from a List with a given Specific Length.

len() function :

The len() function is a Python built-in function.

The length of a string is returned as an integer value by the len() function.

The length of a string can be obtained by passing a string value as a parameter to the len() function.

Examples:

Example1:

Input:

Given List = ['hello', 'btechgeeks', 'good', 'morning']
Given length = 5

Output:

The Items from a given List with given Specific Length : 
hello

Example 2:

Input:

Given List = ['abcd', 'efghigdh', 'kjfatr', 'ihg', 'dfth']
Given length = 4

Output:

The Items from a given List with given Specific Length : 
abcd
dfth

Program to Print Items from a List with Specific Length

Below are the ways to print items from a List with a given Specific Length.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the List of String as static input and store it in a variable.
  • Give the length as static input and store it in another variable.
  • Loop in the above-given list using for loop.
  • Inside the loop, check if the length of the iterator is equal to the given length using the len() function and if conditional statement.
  • If the statement is true, then print the iterator value(i.e. string).
  • The Exit of the program.

Below is the implementation:

# Give the List of String as static input and store it in a variable.
gvn_lst = ['hello', 'btechgeeks', 'good', 'morning']
# Given the length as static input and store it in another variable.
gvn_len = 5
# Loop in the above-given list using for loop.
print("The Items from a given List with given Specific Length : ")
for itr in gvn_lst:
  # Inside the loop, check if the length of the iterator is equal to the given length
  # using len() function and if conditional statement.
    if(len(itr)) == gvn_len:
     # If the statement is true, then print the iterator value(i.e. string).
        print(itr)

Output:

The Items from a given List with given Specific Length : 
hello

Method #2: Using For Loop (User Input)

Approach:

  • Give the List of Strings as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the length as user input using the int(input()) function and store it in another variable.
  • Loop in the above-given list using for loop.
  • Inside the loop, check if the length of the iterator is equal to the given length using len() function and if conditional statement.
  • If the statement is true, then print the iterator value(i.e. string).
  • The Exit of the program.

Below is the implementation:

# Give the List of String as user input using list(),map(),input(),and 
#split() functions and store it in a variable.
gvn_lst = list(map(str, input( 'Enter some random List Elements separated by spaces = ').split()))
# Give the length as user input using int(input())and store it in another variable.
gvn_len = int(input("Enter some random number = "))
# Loop in the above-given list using for loop.
print("The Items from a given List with given Specific Length : ")
for itr in gvn_lst:
  # Inside the loop, check if the length of the iterator is equal to the given length
  # using len() function and if conditional statement.
    if(len(itr)) == gvn_len:
     # If the statement is true, then print the iterator value(i.e. string).
        print(itr)

Output:

Enter some random List Elements separated by spaces = abcd efghigdh kjfatr ihg dfth
Enter some random number = 4
The Items from a given List with given Specific Length : 
abcd
dfth

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Print Items from a List with Specific Length Read More »

Program to Check a Binary Number is Divisible by a Number N

Python Program to Check a Binary Number is Divisible by a Number N

In the previous article, we have discussed Python Program to Pick a Random Card
Binary Number:

A binary number is a number expressed in the base 2 numeral system, which employs only the symbols 0 and 1.

Conversion from binary to decimal:

binary number = 1010

decimal number = int(str(binary number),2)

Given a binary number, and the task is to check if the binary number is divisible by a given number N.

Examples:

Example1:

Input:

Given binary number = 1100
Given number = 4

Output:

The given binary number is divisible by{ 4 }

Example2:

Input:

Given binary number = 1000
Given number = 2

Output:

The given binary number is divisible by{ 2 }

Program to Check a Binary Number is Divisible by a number N.

Below are the ways to check if the given binary number is divisible by a given number N.

Method #1: Using Built-in Functions (Static input)

Approach:

  • Give the binary number as static input and store it in a variable.
  • Given the number as static input and store it in another variable.
  • Convert the given binary number into a decimal number using int(str(binary number),2) function and store it in another variable say “deci”.
  • Check if the above-obtained decimal number modulus given number is equal to 0 using the if conditional statement.
  • If the statement is true, then print “The binary number is divisible by the given input number”.
  • Else print “The binary number is not divisible by the given input number”.
  • The Exit of the program.

Below is the implementation:

# Give the binary number as static input and store it in a variable.
binry = 1100
# Given the number as static input and store it in another variable.
num = 4
# Convert the given binary number into a decimal number using int(str(binary number),2)
# function and store it in another variable say "deci".
deci = int(str(binry), 2)
# Check if the above-obtained decimal number modulus given number is equal to 0 using the if
# conditional statement.
if deci % num == 0:
    # If the statement is true, then print "The binary number is divisible by the given
    # input number".
    print("The given binary number is divisible by{", num, "}")
else:
 # Else print ""The binary number is not divisible by the given input number".
    print("The given binary number is not divisible by{", num, "}")

Output:

The given binary number is divisible by{ 4 }

Method #2: Using Built-in Functions (User input)

Approach:

  • Give the binary number as user input using int(input()) and store it in a variable.
  • Given the number as user input using int(input()) and store it in another variable.
  • Convert the given binary number into a decimal number using int(str(binary number),2) function and store it in another variable say “deci”.
  • Check if the above-obtained decimal number modulus given number is equal to 0 using the if conditional statement.
  • If the statement is true, then print “The binary number is divisible by the given input number”.
  • Else print “The binary number is not divisible by the given input number”.
  • The Exit of the program.

Below is the implementation:

# Give the binary number as user input using int(input()) and store it in a variable.
binry = int(input("Enter some random number = "))
# Given the number as user input using int(input()) and store it in another variable.
num = int(input("Enter some random number = "))
# Convert the given binary number into a decimal number using int(str(binary number),2)
# function and store it in another variable say "deci".
deci = int(str(binry), 2)
# Check if the above-obtained decimal number modulus given number is equal to 0 using the if
# conditional statement.
if deci % num == 0:
    # If the statement is true, then print "The binary number is divisible by the given
    # input number".
    print("The given binary number is divisible by{", num, "}")
else:
 # Else print ""The binary number is not divisible by the given input number".
    print("The given binary number is not divisible by{", num, "}")

Output:

Enter some random number = 1000
Enter some random number = 2
The given binary number is divisible by{ 2 }

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Check a Binary Number is Divisible by a Number N Read More »

Program to Delete Random Item from a List

Python Program to Delete Random Item from a List

In the previous article, we have discussed Python Program to Print Items from a List with Specific Length
Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

The random module is extremely useful for creating a variety of entertaining games.

choice():  choice() is used to select an item at random from a list, tuple, or other collection.

Because the choice() method returns a single element, we will be using it in looping statements.

Examples:

Example1:

Input:

Given List = ['apple', 'mango', 'banana', 'orange']

Output:

The given list after deletion of random item = ['apple', 'banana', 'orange']

Example2:

Input:

Given List = ['good', 'morning', 'btechgeeks', 'hello', 'all']

Output:

The given list after deletion of random item = ['good', 'morning', 'hello', 'all']

Program to Delete Random Item from a List

Below are the ways to Delete Random items from a given List.

Method #1: Using random.choice Method (Static input)

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in another variable.
  • Apply random. choice() method for the above-given list to get the random item and store it in another variable.
  • Remove the above obtained random item from the given list.
  • Print the above-given list after deletion of random items from the list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in another variable.
gvn_lst = ['apple', 'mango', 'banana', 'orange']
# Apply random.choice() method for the above-given list to get the random item and
# store it in another variable.
randm_item = random.choice(gvn_lst)
# Remove the above obtained random item from the given list.
gvn_lst.remove(randm_item)
# Print the above-given list after deletion of random item from the list.
print("The given list after deletion of random item =", gvn_lst)

Output:

The given list after deletion of random item = ['apple', 'banana', 'orange']

Method #2: Using random.choice Method (User input)

Approach:

  • Import random module using the import keyword.
  • Give the List as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Apply random. choice() method for the above-given list to get the random item and store it in another variable.
  • Remove the above obtained random item from the given list.
  • Print the above-given list after deletion of random items from the list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the List as user input using list(),map(),input(),and split() functions and 
#store it in a variable.
gvn_lst = list(map(str, input( 'Enter some random List Elements separated by spaces = ').split()))
# Apply random.choice() method for the above-given list to get the random item and
# store it in another variable.
randm_item = random.choice(gvn_lst)
# Remove the above obtained random item from the given list.
gvn_lst.remove(randm_item)
# Print the above-given list after deletion of random item from the list.
print("The given list after deletion of random item =", gvn_lst)

Output:

Enter some random List Elements separated by spaces = good morning btechgeeks hello all
The given list after deletion of random item = ['good', 'morning', 'hello', 'all']

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Delete Random Item from a List Read More »

Program to Shuffle a List

Python Program to Shuffle a List

In the previous article, we have discussed Python Program to Print a Deck of Cards in Python
To shuffle the elements in a list means to arrange them in random order.

In Python, there are numerous ways to shuffle the elements of a list.

Like using random.shuffle() method , for loop etc.

Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

The random module is extremely useful for creating a variety of entertaining games.

random.shuffle(): To shuffle an object, use random. shuffle().

Given a list and the task is to shuffle the elements of a given list.

Examples:

Example1:

Input:

Given list = ['good', 'morning', 'btechgeeks', '651326', '12345', 'great', 'coding', 'platform']

Output:

The given list after shuffling the elements = ['good', '651326', 'coding', 'platform', 'morning', 'great', 'btechgeeks', '12345']

Example2:

Input:

Given list =['potato' ,'tomato', 'carrot', 'brinjal, 'beetroot']

Output:

The given list after shuffling the elements = ['tomato', 'potato', 'brinjal', 'carrot', 'beetroot']

Program to Shuffle a List

Below are the ways to shuffle a given list.

Method #1: Using random.shuffle() Method (Static input)

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in another variable.
  • Apply random. shuffle() method for the above-given list to shuffle the items of a given list.
  • Print the shuffled list of the given input list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in another variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks', '12345']
# Apply random. shuffle() method for the above-given list to shuffle the items
# of a given list.
random.shuffle(gvn_lst)
# Print the shuffled list of the given input list.
print("The given list after shuffling the elements =", gvn_lst)

Output:

The given list after shuffling the elements = ['this', 'hello', '12345', 'is', 'btechgeeks']

Method #2: Using random.shuffle() Method (User input)

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions and store it in another variable. 
  • Apply random. shuffle() method for the above-given list to shuffle the items of a given list.
  • Print the shuffled list of the given input list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as user input using list(),map(),input(),and split() functions 
#and store it in another variable.
gvn_lst = list(map(str, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Apply random. shuffle() method for the above-given list to shuffle the items
# of a given list.
random.shuffle(gvn_lst)
# Print the shuffled list of the given input list.
print("The given list after shuffling the elements =", gvn_lst)

Output:

Enter some random List Elements separated by spaces = potato tomato carrot brinjal beetroot
The given list after shuffling the elements = ['tomato', 'potato', 'brinjal', 'carrot', 'beetroot']

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Shuffle a List Read More »

Program to Calculate Age in Days from Date of Birth

Python Program to Calculate Age in Days from Date of Birth

In the previous article, we have discussed Python Program to Check Strontio Number or Not.
Given the Date of Birth and task is to calculate the corresponding age in days.

datetime module:

The datetime module contains numerous classes that can be used to manipulate date and time in both simple and complex ways.

In this, the date is formatted as the year month date (YY, MM, DD).

datetime.today() :The current date/system date is returned by datetime.today().

To calculate age from date of birth, subtract the date of birth from the current date.

timedelta() function in Python:

The Python timedelta() function is part of the datetime library and is commonly used for calculating date differences. It can also be used for date manipulation in Python. It is one of the simplest methods for manipulating dates.

Examples:

Example1:

Input:

Given Date of Birth = (2000, 3, 14)

Output:

The age in days and time for the Given DOB =  7823 days, 14:16:13.409557

Example2:

Input:

Given Date of Birth = (1999, 5, 16)

Output:

The age in days and time for the Given DOB = 8126 days, 14:14:30.074853

Program to Calculate Age in Days from Date of Birth

Below are the ways to calculate age in days from the given Date of Birth.

Method #1: Using the datetime Module (Static Input)

Approach:

  • Import datetime(), timedelta() functions from datetime module using import keyword.
  • Give the date of birth as static input in the format (YY, MM, DD) using datetime() function and store it in a variable.
  • Get the current/today date using datetime.today() function and store it in another variable.
  • Subtract the given date of birth from the current date to get the age in days and store it in another variable.
  • Print the age in days and time from the given date of birth.
  • The Exit of the Program.

Note: If we include the timedelta() function we get age in time including microseconds.

If you want age only in days then remove the timedelta() function import only datetime() function.

Below is the implementation:

# Import datetime(), timedelta() functions from datetime module using import keyword.
from datetime import datetime, timedelta
# Give the date of birth as static input in the format (YY, MM, DD) using datetime() function
# and store it in a variable.
gvn_DOB = datetime(1999, 5, 16)
# Get the current/today date using datetime.today() function and store it in
# another variable.
current_date = datetime.today()
# Subtract the given date of birth from the current date to get the age in days
# and store it in another variable.
age_in_days = current_date - gvn_DOB
# Print the age in days and time from the given date of birth.
print("The age in days and time for the Given DOB = ", age_in_days)

Output:

The age in days and time for the Given DOB =  8126 days, 14:14:30.074853

Method #2: Using the datetime Module (User Input)

Approach:

  • Import datetime(), timedelta() functions from datetime module using import keyword.
  • Give the year, month, day as user input using map (), int(), split() functions and store them separately in three different variables.
  • Convert the year, month, day to date of birth using datetime() module and store it in another variable.
  • Get the current/today date using datetime.today() function and store it in another variable.
  • Subtract the given date of birth from the current date to get the age in days and store it in another variable.
  • Print the age in days and time from the given date of birth.
  • The Exit of the Program.

Below is the implementation:

# Import datetime(), timedelta() functions from datetime module using import keyword.
from datetime import datetime, timedelta
# Give the year, month, day as user input using map (), int(), split() functions 
#and store them separately in three different variables.
yr,mont,dy= map(int,input("Enter year ,month ,day separated by spaces = ").split())
#Convert the year, month, day to date of birth using datetime() module and store it in another variable.
gvn_DOB=datetime(yr, mont, dy)
# Get the current/today date using datetime.today() function and store it in
# another variable.
current_date = datetime.today()
# Subtract the given date of birth from the current date to get the age in days
# and store it in another variable.
age_in_days = current_date - gvn_DOB
# Print the age in days and time from the given date of birth.
print("The age in days and time for the Given DOB = ", age_in_days)

Output:

Enter year ,month ,day separated by spaces = 2003 7 19
The age in days and time for the Given DOB = 6601 days, 14:47:41.427259

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Calculate Age in Days from Date of Birth Read More »

Program to Divide a String in 'N' Equal Parts

Python Program to Divide a String in ‘N’ Equal Parts

In the previous article, we have discussed Python Program to Check Evil Number or Not
Given a string and the task is to divide the given string into “N” equal parts.

Examples:

Example1:

Input:

Given string = "aaaabbbbccccddddeeee"

Output:

The given string after dividing into 5 equal halves:
aaaa
bbbb
cccc
dddd
eeee

Example2:

Input:

Given string = "hellobtechgeeks"

Output:

The given string cannot be divided into 4 equal halves

Program to Divide a String in ‘N’ Equal Parts

Below are the ways to divide the given string into “N” equal parts.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the number say ‘n’ as static input and store it in another variable.
  • Calculate the len of the given string using the len() function and store it in another variable.
  • Check if the length of the string modulus given number is not equal to ‘0’ or not using the if conditional statement.
  • If the statement is true, print “The given string cannot be divided into n equal halves”.
  • Else loop from 0 to length of the string with the step size of given number ‘n’ using the for loop.
  • Slice from the iterator value to the iterator +n value using slicing and print them.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "aaaabbbbccccddddeeee"
# Give the number say 'n' as static input and store it in another variable.
num = 5
# Calculate the len of the given string using the len() function and store it
# in another variable.
len_str = len(gvn_str)
# Divide the length of the string by a given number and store it in another variable say 'k'.
k = len_str//num
# Check if the length of the string modulus given number is not equal to '0' or
# not using the if conditional statement.
if(len_str % num != 0):
    # If the statement is true, print "The given string cannot be divided into n equal halves".
    print("The given string cannot be divided into", num, "equal halves")
else:
  # Else loop from 0 to length of the string with the step size of the number 'k'
  # using the for loop.
    print("The given string after dividing into", num, "equal halves:")
    for i in range(0, len_str, k):
        # Slice from the iterator value to the iterator +n value using slicing and
        # print them.
        print(gvn_str[i:i+k])

Output:

The given string after dividing into 5 equal halves:
aaaa
bbbb
cccc
dddd
eeee

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 say ‘n’ as static input and store it in another variable.
  • Calculate the len of the given string using the len() function and store it in another variable.
  • Divide the length of the string by a given number and store it in another variable say ‘k’.
  • Check if the length of the string modulus given number is not equal to ‘0’ or not using the if conditional statement.
  • If the statement is true, print “The given string cannot be divided into n equal halves”.
  • Else loop from 0 to length of the string with the step size of the number ‘k’ using the for loop.
  • Slice from the iterator value to the iterator +k value using slicing and print them.
  • 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.
gvn_str = input("Enter some random string = ")
# Give the number say 'n' as user input using int(input()) and store it in another variable.
num = int(input("Enter some random number = "))
# Calculate the len of the given string using the len() function and store it
# in another variable.
len_str = len(gvn_str)
#Divide the length of the string by a given number and store it in another variable say 'k'.
k=len_str//num
# Check if the length of the string modulus given number is not equal to '0' or
# not using the if conditional statement.
if(len_str % num != 0):
    # If the statement is true, print "The given string cannot be divided into n equal halves".
    print("The given string cannot be divided into", num, "equal halves")
else:
  # Else loop from 0 to length of the string with the step size of the number 'k'
  # using the for loop.
    print("The given string after dividing into", num, "equal halves:")
    for i in range(0, len_str, k):
        # Slice from the iterator value to the iterator +n value using slicing and
        # print them.
        print(gvn_str[i:i+k])

Output:

Enter some random string = 1234567890
Enter some random number = 2
The given string after dividing into 2 equal halves:
12345
67890

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Divide a String in ‘N’ Equal Parts Read More »

Program to Find nth Prime Number

Python Program to Find nth Prime Number

In the previous article, we have discussed Python Program to Delete Random Item from a List
Prime Number :

A prime number is one that can only be divided by one and itself.

Given a number ‘n’, and the task to find the nth prime number.

Examples:

Example1:

Input:

Given number = 8

Output:

The above given nth Prime Number is =  19

Example2:

Input:

Given number = 3

Output:

The above given nth Prime Number is =  5

Program to Find nth Prime Number

Below are the ways to find the nth prime number.

Method #1: Using While, For Loop (Static Input)

Approach:

  • Give the number say ‘n’ as static input and store it in a variable.
  • Take a list say ‘prime_numbers’ and initialize it with 2, 3 values.
  • Take a variable and initialize it with 3 say ‘x’.
  • Check if the given number is between greater than 0 and less than 3 using the if conditional statement.
  • If the statement is true, then print the value of the list “prime_numbers[n-1] “.
  • Check if the given number is greater than 2 using the elif conditional statement.
  • Iterate the loop infinite times using the while loop i.e while(True).
  • Inside the loop increment the value of the above given ‘x’ variable by ‘1’.
  • Take a variable to say ‘y’ and initialize with ‘True’.
  • Loop from 2 to int((x/2)+1) using the for loop and int function().
  • Check if the value of variable ‘x’ modulus iterator value is equal to zero or not using the if conditional statement.
  • If the statement is true, assign “False” to the variable y, break the statement and come out of the loop.
  • Check if variable y is equal to True using the if conditional statement.
  • If the statement is true, then append the value of variable ‘x’ to the above list ‘prime_numbers’.
  • Check if the length of the above list ‘prime_numbers’ is equal to the given number.
  • If the statement is true, then give a break statement and come out of the while loop.
  • Print the value of the list “prime_numbers[n-1]” to get the nth prime number.
  • Else print “Invalid number. Please enter another number “.
  • The Exit of the Program.

Below is the implementation:

# Give the number say 'n' as static input and store it in a variable.
num = 5
# Take a list say 'prime_numbers' and initialize it with 2, 3 values.
prim_numbrs = [2, 3]
# Take a variable and initialize it with 3 say 'x'.
x = 3
# Check if the given number is between greater than 0 and less than 3 using the if
# conditional statement.
if(0 < num < 3):
 # If the statement is true, then print the value of the list "prime_numbers[n-1] ".
    print('The above given nth Prime Number is =', prim_numbrs[num-1])
# Check if the given number is greater than 2 using the elif conditional statement.
elif(num > 2):
  # Iterate the loop infinite times using the while loop i.e while(True).
    while (True):
     # Inside the loop increment the value of the above given 'x' variable by '1'.
        x += 1
 # Take a variable say 'y' and initialize with 'True'.
        y = True
  # Loop from 2 to int((x/2)+1) using the for loop and int function().
        for itr in range(2, int(x/2)+1):
          # Check if the value of variable 'x' modulus iterator value is equal to zero or not
          # using the if conditional statement.
            if(x % itr == 0):
                # If the statement is true, assign "False" to the variable y, break the statement and
                # come out of the loop.
                y = False
                break
 # Check if variable y is equal to True using the if conditional statement.
        if(y == True):
            # If the statement is true, then append the value of variable 'x' to the
            # above list 'prime_numbers'.
            prim_numbrs.append(x)
  # Check if the length of the above list 'prime_numbers' is equal to the given number.
        if(len(prim_numbrs) == num):
         # If the statement is true, then give a break statement and come out of the while loop.
            break
 # Print the value of the list "prime_numbers[n-1]" to get the nth prime number.
    print('The above given nth Prime Number is = ', prim_numbrs[num-1])
 # Else print "Invalid number. Please enter another number ".
else:
    print("Invalid number. Please enter another number ")

Output:

The above given nth Prime Number is =  11

Method #2: Using While, For Loop (User Input)

Approach:

  • Give the number say ‘n’ as user input using int(input()) and store it in a variable.
  • Take a list say ‘prime_numbers’ and initialize it with 2, 3 values.
  • Take a variable and initialize it with 3 say ‘x’.
  • Check if the given number is between greater than 0 and less than 3 using the if conditional statement.
  • If the statement is true, then print the value of the list “prime_numbers[n-1] “.
  • Check if the given number is greater than 2 using the elif conditional statement.
  • Iterate the loop infinite times using the while loop i.e while(True).
  • Inside the loop increment the value of the above given ‘x’ variable by ‘1’.
  • Take a variable to say ‘y’ and initialize with ‘True’.
  • Loop from 2 to int((x/2)+1) using the for loop and int function().
  • Check if the value of variable ‘x’ modulus iterator value is equal to zero or not using the if conditional statement.
  • If the statement is true, assign “False” to the variable y, break the statement and come out of the loop.
  • Check if variable y is equal to True using the if conditional statement.
  • If the statement is true, then append the value of variable ‘x’ to the above list ‘prime_numbers’.
  • Check if the length of the above list ‘prime_numbers’ is equal to the given number.
  • If the statement is true, then give a break statement and come out of the while loop.
  • Print the value of the list “prime_numbers[n-1]” to get the nth prime number.
  • Else print “Invalid number. Please enter another number “.
  • The Exit of the Program.

Below is the implementation:

# Give the number say 'n' as user input using int(input()) and store it in a variable.
num = int(input("Enter some random number = "))
# Take a list say 'prime_numbers' and initialize it with 2, 3 values.
prim_numbrs = [2, 3]
# Take a variable and initialize it with 3 say 'x'.
x = 3
# Check if the given number is between greater than 0 and less than 3 using the if
# conditional statement.
if(0 < num < 3):
 # If the statement is true, then print the value of the list "prime_numbers[n-1] ".
    print('The above given nth Prime Number is =', prim_numbrs[num-1])
# Check if the given number is greater than 2 using the elif conditional statement.
elif(num > 2):
  # Iterate the loop infinite times using the while loop i.e while(True).
    while (True):
     # Inside the loop increment the value of the above given 'x' variable by '1'.
        x += 1
 # Take a variable say 'y' and initialize with 'True'.
        y = True
  # Loop from 2 to int((x/2)+1) using the for loop and int function().
        for itr in range(2, int(x/2)+1):
          # Check if the value of variable 'x' modulus iterator value is equal to zero or not
          # using the if conditional statement.
            if(x % itr == 0):
                # If the statement is true, assign "False" to the variable y, break the statement and
                # come out of the loop.
                y = False
                break
 # Check if variable y is equal to True using the if conditional statement.
        if(y == True):
            # If the statement is true, then append the value of variable 'x' to the
            # above list 'prime_numbers'.
            prim_numbrs.append(x)
  # Check if the length of the above list 'prime_numbers' is equal to the given number.
        if(len(prim_numbrs) == num):
         # If the statement is true, then give a break statement and come out of the while loop.
            break
 # Print the value of the list "prime_numbers[n-1]" to get the nth prime number.
    print('The above given nth Prime Number is = ', prim_numbrs[num-1])
 # Else print "Invalid number. Please enter another number ".
else:
    print("Invalid number. Please enter another number ")

Output:

Enter some random number = 1
The above given nth Prime Number is = 2

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Find nth Prime Number Read More »