Reversal of a string

startmsg = "hello"
endmsg = ""
for i in range(0,len(startmsg)):
  endmsg = startmsg[i] + endmsg
print (endmsg)

String replacing with another string with occurrence count

s='brown box red pencil brown pen red pen red box'
print (s)
s1=s.replace('red','brown')
print (s1)

s='brown box red pencil brown pen red pen red box'
print (s)
s1=s.replace('brown','red',1)
print (s1)

s='brown box red pencil brown pen red pen red box'
print (s)
s1=s.replace('brown','red',2)
print (s1)

s='brown box red pencil brown pen red pen red box'
print (s)
s1=s.replace('brown','red',3)
print (s1)

Searching the pattern in a String using find and index

try:
    s="brown box red pencil brown pen red pen red box"
    print s.find("red")
    print s.find("red",13,len(s))
    print s.find("red",34,len(s))
    print s.find("crow")
    print s.index("red")
    print s.index("red",13,len(s))
    print s.index("red",34,len(s))
    print s.index("crow")
except ValueError:
   print "crow not a pattern in string"
   

String operations to remove white spaces

s=" t  ioi ii "
t1=s.rstrip() # removes trailing white space
t2=s.lstrip() # removes leading white space
t3=s.strip()  # removes leading and trailing white space

print s

print t1

print t2

print t3

File operation for copying content of one file to another without for loop

#  Implementation without for loop
#  Copying content of 1.txt file to 2.txt after creation of file
#  Please provide the 1.txt file in the current folder as input and
#  check after runing the program in the same folder for 2.txt

I=open('1.txt',"r")
O=open('2.txt',"w")
C=I.readlines()
O.writelines(C)
I.close()
O.close()

File operation for copying content of one file to another

#  Copying content of 1.txt file to 2.txt after creation of file
#  Please provide the 1.txt file in the current folder as input and
#  check after runing the program in the same folder for 2.txt

I=open('1.txt',"r")
O=open('2.txt',"w")
for l in I.readlines():
    O.write(l)
I.close()
O.close()

Exceptional handling for Zero Division Error

# if value of x is given as zero the zero divison error generates and program terminates
x=int(raw_input('Enter the number of students failed:'))
y=100/x
print y


# If x is not defined itself the program not terminated instead it goes to except loop
try:
    x=int(raw_input('Enter the number of students failed:'))
    y=100/x
    print y
except ZeroDivisionError:
    x=1
    y=100/x
    print y

Exceptional handling for Name Error

# If x is not defined itself the program not terminated
try:
    y=50*x
except NameError:
    x=1
    y=50*x
    print y
   

Exceptional handling for Key Error

#Without Exceptional handling program terminates if key b not found
s={'d':2,'k':4}
if b in s.keys():
    s['b'].append[9]
else:
    s['b']= 8


#Exceptional handling for key error and program run without termination
s={'d':2,'k':4}
try:
    s['b'].append[9]
except KeyError:
    s['b']= 8