Categories
Python Answers

How to find the nth occurrence of substring in a string with Python?

Sometimes, we want to find the nth occurrence of substring in a string with Python.

In this article, we’ll look at how to find the nth occurrence of substring in a string with Python.

How to find the nth occurrence of substring in a string with Python?

To find the nth occurrence of substring in a string with Python, we can use a loop to find it.

For instance, we write:

def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start + len(needle))
        n -= 1
    return start


index = find_nth("foofoofoofoo", "foofoo", 2)
print(index)

to define the find_nth function that searches the haystack string for the needle.

And we want to find the nth occurrence of it.

In the function, we call haystack.find with needle to find the index of the first occurrence of needle.

If start is bigger than or equal to 0 and n is bigger than 1, then we start the while loop to use haystack.find(needle, start + len(needle)) to update start until n becomes 0.

Finally, we return start which is the first index of the nth occurrence of the needle.

Therefore, index is 6.

Conclusion

To find the nth occurrence of substring in a string with Python, we can use a loop to find it.

Categories
Python Answers

How to append the same string to a list of strings in Python?

Sometimes, we want to append the same string to a list of strings in Python.

In this article, we’ll look at how to append the same string to a list of strings in Python.

How to append the same string to a list of strings in Python?

To append the same string to a list of strings in Python, we can use list comprehension.

For instance, we write:

list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
list2 = [s + string for s in list1]
print(list2)

We concatenate string to each entry s in list1.

And then we assign the returned list to list2.

Therefore, list2 is ['foobar', 'fobbar', 'fazbar', 'funkbar'].

Conclusion

To append the same string to a list of strings in Python, we can use list comprehension.

Categories
Python Answers

How to print a string at a fixed width with Python?

Sometimes, we want to print a string at a fixed width with Python.

In this article, we’ll look at how to print a string at a fixed width with Python.

How to print a string at a fixed width with Python?

To print a string at a fixed width with Python, we can use the string’s format method with a format code.

For instance, we write:

s = '{0: <5}'.format('s')
print(s)

to return a string with length 5.

The 's' string is padded to length 5 with empty trailing spaces.

Therefore, print prints ''s '.

Conclusion

To print a string at a fixed width with Python, we can use the string’s format method with a format code.

Categories
Python Answers

How to get the MD5 hash of big files in Python?

Sometimes, we want to get the MD5 hash of big files in Python.

In this article, we’ll look at how to get the MD5 hash of big files in Python.

How to get the MD5 hash of big files in Python?

To get the MD5 hash of big files in Python, we can use the md5.update and md5.digest methods.

For instance, we write:

import hashlib
import os


def generate_file_md5(rootdir, filename, blocksize=2**20):
    m = hashlib.md5()
    with open(os.path.join(rootdir, filename), "rb") as f:
        while True:
            buf = f.read(blocksize)
            if not buf:
                break
            m.update(buf)
    return m.hexdigest()


print(generate_file_md5('', 'img.png'))

We create the generate_file_md5 function that takes the rootdir, filename, and blocksize parameters.

In the function, we open the file with open with 'rb' permission to let us read the file in blocks.

We use os.path.join(rootdir, filename) to get the full path of the file.

Next, we have a while loop that loops through each block of the file that’s read with f.read.

And we call m.update on each block that’s read to update the md5 hash after each block is read.

Finally, we return md5 hash of the full file with m.hexdigest().

As a result, the print output should be something like 'b60ab2708daec7685f3d412a5e05191a'.

Conclusion

To get the MD5 hash of big files in Python, we can use the md5.update and md5.digest methods.

Categories
Python Answers

How to do frequency counts for unique values in an array with Python NumPy?

Sometimes, we want to do frequency counts for unique values in an array with Python NumPy.

In this article, we’ll look at how to do frequency counts for unique values in an array with Python NumPy.

How to do frequency counts for unique values in an array with Python NumPy?

To do frequency counts for unique values in an array with Python NumPy, we can use the unique method.

For instance, we write:

import numpy as np

x = np.array([1, 1, 1, 2, 2, 2, 5, 25, 1, 1])
unique, counts = np.unique(x, return_counts=True)

print(np.asarray((unique, counts)).T)

to create an array with np.array.

Then we call np.unique on array x and set return_counts to True to return the count of each item in the x array.

Finally, we call np.asarray with unique and counts in an tuple and get the T property to get the items and their counts in a nested list.

Therefore, we see:

[[ 1  5]
 [ 2  3]
 [ 5  1]
 [25  1]]

printed.

Conclusion

To do frequency counts for unique values in an array with Python NumPy, we can use the unique method.