PYTHON PROGRAM TO REPLACE WORDS FROM A STRING EASY EXAMPLE

 Que- How to change words in a string in python?

Ans- To change a word in a string in python we use str_name.replace("replace word","change word") to  by using this function we are able to change words in a string in python.

Example of replace word in a string in python:-

This example show a student name, grade, date , gender is change by their respective data by using str_name.replace("replace word","change word") .

Steps to write the program:-

  1. In first step we given a string (show) and define it. 
  2. In next step we make variable like(name, math, science, English, Hindi, sst, date,gen,res).And take input into these variables by using input(" ") function. 
  3. In next step convert strings like( math, science, English, Hindi, sst) in int type so that we can calculate them and find the average percentage of the student. And equal all these strings to the res string to store the result.
  4. In next step we use if-else statements to check the gender value either it is male , female or other to give proper English honorific according to gender.
  5. Then we use str_name.replace("replace word","change word") function to replace required words with input data from the user.
  6. Then last print the value of show
Syntax for the program:-

show='''Mr/Ms studentname is passed with grade % in year date'''
name=input("enter student name :- ")
math=input("enter marks in maths :- ")
science=input("enter marks in science :- ")
English=input("enter marks in English :- ")
Hindi=input("enter marks in hindi :- ")
sst=input("enter marks in social science :- ")
date=input("enter year :- ")
gen=input("enter your gender :- ")
res=((int(math)+int(science)+int(English)+int(Hindi)+int(sst))/5)
res=str(res)
if gen=="male" or gen=="Male":
 show=show. replace('Mr/Ms'," Mr.")
if gen=="female" or gen=="Female":
 show=show. replace('Mr/Ms'," Ms.")
show=show.replace('studentname',name)
show=show.replace('grade',res)
show=show.replace('date',date)
print (show)

Result:-




Post a Comment

Previous Post Next Post