Monday, 4 September 2017

Python Q & A

The method join() returns a string in which the string elements of sequence have been joined by str separator.

s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )
Replace method
#!/usr/bin/python

str = "this is string example....wow!!! this is really string"
print str.replace("is", "was") #thwas was string example....wow!!! thwas was really string
print str.replace("is", "was", 3)#thwas was string example....wow!!! thwas is really string
 
Difference between remove and del
remove removes the first matching value, not a specific index:
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

del removes a specific index:
>>> a = [3, 2, 2, 1]
>>> del a[1]
[3, 2, 1]

What Is The Command To Debug A Python Program?

$ python -m pdb python-script.py

 Do You Monitor The Code Flow Of A Program In Python?

In Python, we can use <sys> module’s <settrace()> method to setup trace hooks and monitor the functions inside a program.
You need to define a trace callback method and pass it to the <settrace()> method. The callback should specify three arguments as shown below.
import sys
 
def trace_calls(frame, event, arg):
    # The 'call' event occurs before a function gets executed.
    if event != 'call':
        return
    # Next, inspect the frame data and print information.
    print 'Function name=%s, line num=%s' % (frame.f_code.co_name, frame.f_lineno)
    return
 
def demo2():
    print 'in demo2()'
 
def demo1():
    print 'in demo1()'
    demo2()
 
sys.settrace(trace_calls)
demo1()
  

Max method

print "max(80, 100, 1000) : ", max(80, 100, 1000) #1000
print "max(-20, 100, 400) : ", max(-20, 100, 400) #400 
print "max(-80, -20, -10) : ", max(-80, -20, -10) #-10

No comments:

Post a Comment