Found 10418 Articles for Python

How to find and replace within a text file using Python?

Rajendra Dharmkar
Updated on 19-Feb-2020 12:13:43

414 Views

The following code does the replacement in the given text file. After the replacement, the text is written to a new text file 'bar.txt'Examplef1 = open('foo.txt', 'r') f2 = open('bar.txt', 'w') for line in f1:     print line     f2.write(line.replace('Poetry', 'Prose')) f2 = open('bar.txt', 'r') for line in f2:    print line, f1.close() f2.close()OutputThis gives the outputPoetry is often considered the oldest form of literature. Poetry today is usually  written down, but is still sometimes performed. Prose is often considered the oldest form of literature. Prose today is usually written down, but is still sometimes performed.Read More

Can we assign a reference to a variable in Python?

Malhar Lathkar
Updated on 20-Feb-2020 08:11:01

1K+ Views

Concept of variable in Python is different from C/C++. In C/C++, variable is a named location in memory. Even if value of one is assigned to another, it creates a copy in another location.int x=5; int y=x;For example in C++, the & operator returns address of the declared variable.cout

How can we unpack a string of integers to complex numbers in Python?

Malhar Lathkar
Updated on 20-Feb-2020 08:09:49

177 Views

A string contains two integers separated by comma. It is first split in a list of two strings having digits.>>> s="1,2".split(",") >>> s ['1', '2']Two items are then converted to integers and used as arguments for complex() function>>> complex(int(s[0]), int(s[1])) (1+2j)This results in unpacking of string of integers in a complex number

How we can iterate through a Python list of tuples?

Malhar Lathkar
Updated on 20-Feb-2020 08:07:37

8K+ Views

Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=’ ‘ to print all items in a tuple in one line. Another print() introduces new line after each tuple.ExampleL=[(1,2,3), (4,5,6), (7,8,9,10)] for x in L:   for y in x:     print(y, end=' ')   print()Output1 2 3 4 5 6 7 8 9 10

How to iterate through a tuple in Python?

Pythonic
Updated on 19-Dec-2019 09:06:37

5K+ Views

There are different ways to iterate through a tuple object. The for statement in Python has a variant which traverses a tuple till it is exhausted. It is equivalent to foreach statement in Java. Its syntax is −for var in tuple: stmt1 stmt2ExampleFollowing script will print all items in the listT = (10, 20, 30, 40, 50) for var in T: print (T.index(var), var)OutputThe output generated is −0 10 1 20 2 30 3 40 4 50Another approach is to iterate over range upto length of tuple, and use it as index of item in tupleExamplefor var in range(len(T)):   ... Read More

What is the best way to handle list empty exception in Python?

Malhar Lathkar
Updated on 19-Dec-2019 09:26:52

2K+ Views

List is an ordered sequence of elements. Individual element in list is accessed using index starting with 0 and goes up to length-1. If index goes beyond this range, IndexError exception is encountered.In following example, an infinite loop is used to pop one element at a time. As loop tries to go even after last element is popped, IndexError exception will be encountered. We trap it using try – except mechanism.a=[1,2,3] while True:   try:     b=a.pop()     print (b)   except (IndexError):     break

How to get length of a list of lists in Python?

Malhar Lathkar
Updated on 19-Dec-2019 09:23:22

305 Views

You can employ a nested loop to count number of elements in each sublist of a list>>> a=[[1, 2, 3], [4, 5, 6]] >>> c=0 >>> for x in a:       for y in x:       c=c+1 >>> c 6

How to compare two strings using regex in Python?

Rajendra Dharmkar
Updated on 19-Dec-2019 08:49:48

1K+ Views

We can compare given strings using the following codeExampleimport re s1 = 'Pink Forest' s2 = 'Pink Forrest' if bool(re.search(s1,s2))==True:    print 'Strings match' else:    print 'Strings do not match'OutputThis gives the outputStrings do not match

How do nested functions work in Python?

Vikram Chiluka
Updated on 28-Sep-2023 01:30:40

8K+ Views

In this article, we will explain nested/inner functions in Python and how they work with examples. Nested (or inner) functions are functions defined within other functions that allow us to directly access the variables and names defined in the enclosing function. Nested functions can be used to create closures and decorators, among other things. Defining an inner/nested Function Simply use the def keyword to initialize another function within a function to define a nested function. The following program is to demonstrate the inner function in Python − Example # creating an outer function def outerFunc(sample_text): sample_text ... Read More

What is the difference between Python functions datetime.now() and datetime.today()?

Rajendra Dharmkar
Updated on 13-Jun-2020 06:04:46

2K+ Views

The function datetime.now() takes tzinfo as keyword argument but datetime.today() does not take any keyword arguments. Quoting the docs −datetime.now() returns the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).

Advertisements