Categories
Python Answers

How to find common substrings between two strings with Python?

Sometimes, we want to find common substrings between two strings with Python.

In this article, we’ll look at how to find common substrings between two strings with Python.

How to find common substrings between two strings with Python?

To find common substrings between two strings with Python, we can use the difflib module.

For instance, we write:

from difflib import SequenceMatcher

string1 = "apple pie available"
string2 = "come have some apple pies"

match = SequenceMatcher(None, string1,
                        string2).find_longest_match(0, len(string1), 0,
                                                    len(string2))

print(match)
print(string1[match.a:match.a + match.size])
print(string2[match.b:match.b + match.size])

We have 2 strings string1 and string2 that we want to find the common substring that’s in both strings.

To do that, we use the SequenceMatcher class with string1 and string2.

And we call the find_longest_match method with the indexes for both strings to search for.

Finally, we get the substring that matched from the match object, which has the start and index of the matches with match.a and match.a + match.size for the first string and match.b and match.b + match.size for the 2nd string respectively.

As a result, we see:

Match(a=0, b=15, size=9)
apple pie
apple pie

printed.

Conclusion

To find common substrings between two strings with Python, we can use the difflib module.

Categories
Python Answers

How to get a weighted random selection with and without replacement with Python?

Sometimes, we want to get a weighted random selection with and without replacement with Python.

In this article, we’ll look at how to get a weighted random selection with and without replacement with Python.

How to get a weighted random selection with and without replacement with Python?

To get a weighted random selection with and without replacement with Python, we can use NumPy’s random module.

For instance, we write:

import numpy.random as rnd

sampling_size = 3
domain = ['white', 'blue', 'black', 'yellow', 'green']
probs = [.1, .2, .4, .1, .2]
sample = rnd.choice(domain, size=sampling_size, replace=False, p=probs)
print(sample)

We have a list of choices to choose from from the domain list.

probs has the probability of each value being chosen.

Next, we call rnd.choice with the domain, size, replace and p.

size is the number of choices to make.

replace set to False means the chosen item won’t be a choice again.

And p is the probabilities of each item being chosen.

Therefore, sample is something like ['green' 'blue' 'yellow'].

Conclusion

To get a weighted random selection with and without replacement with Python, we can use NumPy’s random module.

Categories
Python Answers

How to get a random value from dictionary with Python?

Sometimes, we want to get a random value from dictionary with Python.

In this article, we’ll look at how to get a random value from dictionary with Python.

How to get a random value from dictionary with Python?

To get a random value from dictionary with Python, we can use the random.choice method with the dictionary’s values method.

For instance, we write:

import random

d = {'VENEZUELA': 'CARACAS', 'CANADA': 'OTTAWA'}
c = random.choice(list(d.values()))
print(c)

We have the dictionary d which we want to get a random choice from.

Then we call d.values to return a generator with the dictionary’s values.

Next we convert to a list with list.

And then we pick a random choice from the list with random.choice.

Conclusion

To get a random value from dictionary with Python, we can use the random.choice method with the dictionary’s values method.

Categories
Python Answers

How to combine several images horizontally with Python?

Sometimes, we want to combine several images horizontally with Python.

In this article, we’ll look at how to combine several images horizontally with Python.

How to combine several images horizontally with Python?

To combine several images horizontally with Python, we can use the PIL module.

For instance, we write:

from PIL import Image

images = [Image.open(x) for x in ['test1.png', 'test2.jpg']]
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
    new_im.paste(im, (x_offset, 0))
    x_offset += im.size[0]

new_im.save('test.jpg')

We open all the images with:

images = [Image.open(x) for x in ['test1.png', 'test2.jpg']]

Then we get widths and heights of all the images and put them in lists with:

widths, heights = zip(*(i.size for i in images))

Then we get the total width and max height with:

total_width = sum(widths)
max_height = max(heights)

which we set as the dimensions of the combined image.

Next, we combine the pixels from both images into a new image with:

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
    new_im.paste(im, (x_offset, 0))
    x_offset += im.size[0]

The pixels are pasted with:

new_im.paste(im, (x_offset, 0))

Finally, we save the image with new_im.save('test.jpg').

Conclusion

To combine several images horizontally with Python, we can use the PIL module.

Categories
Python Answers

How to convert a date string to date object with Python?

Sometimes, we want to convert a date string to date object with Python.

In this article, we’ll look at how to convert a date string to date object with Python.

How to convert a date string to date object with Python?

To convert a date string to date object with Python, we can use the datetime.datetime.strptime method.

For instance, we write:

import datetime

d = datetime.datetime.strptime('24052010', "%d%m%Y").date()
print(d)

to convert the '24052010' string into a date object.

We parse the string by passing in "%d%m%Y" as the format string.

%d is the 2 digit date of the month.

%m is the 2 digit month.

And %Y is the 4 digit year.

Then we call date to return the date from the date time object.

Therefore, d is 2010-05-24.

Conclusion

To convert a date string to date object with Python, we can use the datetime.datetime.strptime method.