Template Strings, zip() and Enumerate() Functions in Python

Day 26 in #100DaysOfCode

As I have learned many of the basics of Python previously, now I want to cover up some of the important details that are very important. So let's dig in.

Template Strings

This is a simpler string formatting method.

from string import Template
def main():
    templ = Template("You are reading ${book} by ${author}")
    str=templ.substitute(book="Orlando", author="Virginia Woolf")
    print(str)

if __name__=="__main__":
    main()

Output:

You are reading Orlando by Virginia Woolf

Process finished with exit code 0

This is very similar to dictionaries in Python. Check: ilkecandan.hashnode.dev/dictionaries-in-pyt..

Enumerate() Function

When working with iterators, we frequently need to keep track of the number of iterations. Python makes it easier for programmers by including an enumerate() function. Enumerate() adds a counter to an iterable and returns it as an enumerating object. This enumerated object may then be looped on directly or turned into a list of tuples using the list() function.

Example:

# Python program to illustrate enumerate function
a1 = ["morning", "afternoon", "night"]
s1 = "sleep"

# creating enumerate objects
obj1 = enumerate(a1)
obj2 = enumerate(s1)

print ("Return type:", type(obj1))
print (list(enumerate(a1)))

# changing start index to 2 from 0
print (list(enumerate(s1, 2)))

Output:

Return type: <class 'enumerate'>
[(0, 'morning'), (1, 'afternoon'), (2, 'night')]
[(2, 's'), (3, 'l'), (4, 'e'), (5, 'e'), (6, 'p')]

Process finished with exit code 0

zip() Function

It can combine sequences. The zip() method produces a zip object, which is an iterator of tuples in which the first item in each supplied iterator is paired together, followed by the second item in each passed iterator, and so on.

If the lengths of the provided iterators differ, the length of the new iterator is determined by the iterator with the fewest items.

a = ("Jack", "Charlie", "Mike")
c = ("Jeremy", "Christy", "Manny", "Vicky")

x = zip(a, c)
print(tuple(x))

Output:

(('Jack', 'Jeremy'), ('Charlie', 'Christy'), ('Mike', 'Manny'))

Process finished with exit code 0