Categories
Python Answers

How to change one character in a string with Python?

Sometimes, we want to change one character in a string with Python.

In this article, we’ll look at how to change one character in a string with Python.

How to change one character in a string with Python?

To change one character in a string with Python, we can convert the string to a list with list.

Then we change the character at the given list index.

And then we convert the list back to a string with join.

For instance, we write:

text = 'abcdefg'
new = list(text)
new[6] = 'W'
s = ''.join(new)
print(s)

We call list with text to convert text to the new list.

Then we set the character at index 6 of the list to 'W'.

Next, we call ''.join with new to convert new back to a string and assign the returned string to s.

Therefore, s is 'abcdefW'.

Conclusion

To change one character in a string with Python, we can convert the string to a list with list.

Then we change the character at the given list index.

And then we convert the list back to a string with join.

Categories
Python Answers

How to resize an image using PIL and maintain its aspect ratio with Python?

Sometimes, we want to resize an image using PIL and maintain its aspect ratio with Python.

In this article, we’ll look at how to resize an image using PIL and maintain its aspect ratio with Python.

How to resize an image using PIL and maintain its aspect ratio with Python?

To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image.open.

Then we calculate the new width and height to scale the image to according to the new width.

And then we resize the image with the resize method and save the new image with the save method.

For instance, we write:

from PIL import Image

basewidth = 300
img = Image.open('test1.png')
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save('somepic.png')

We set the new width with:

basewidth = 300

Then we open the image with:

img = Image.open('test1.png')

Next, we compute the scale factor with:

wpercent = (basewidth / float(img.size[0]))

Then we get the height of the image with:

hsize = int((float(img.size[1]) * float(wpercent)))

Next, we write:

img = img.resize((basewidth, hsize), Image.ANTIALIAS)

to resize the image.

We use Image.ANTIALIAS to apply image anti-aliasing while resizing.

And finally, we call image.save with the file path to save to to save the resized image.

Conclusion

To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image.open.

Then we calculate the new width and height to scale the image to according to the new width.

And then we resize the image with the resize method and save the new image with the save method.

Categories
Python Answers

How to fix the “datetime.datetime not JSON serializable” error in Python?

Sometimes, we’ve to fix the "datetime.datetime not JSON serializable" error in Python.

In this article, we’ll look at how to fix the "datetime.datetime not JSON serializable" error in Python.

How to fix the "datetime.datetime not JSON serializable" error in Python?

To fix the "datetime.datetime not JSON serializable" error in Python, we can use the json.dumps method.

For instance, we write:

from datetime import date, datetime
from json import dumps


def json_serial(obj):
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError("Type %s not serializable" % type(obj))


s = dumps(datetime.now(), default=json_serial)
print(s)

We create the json_serial function to serialize the datetime object into a string.

In the function,. we call isinstance with obj and (datetime, date) to check if obj that we’re trying to serialize is a date or datetime object.

If it is, then we return obj.isoformat to return a date string.

Otherwise, we raise a TypeError.

Next, we call dumps with a datetime object and set default to json_serial to use json_serial to do the serialization.

Therefore s is "2021-10-20T00:13:35.533502".

Conclusion

To fix the "datetime.datetime not JSON serializable" error in Python, we can use the json.dumps method.

Categories
Python Answers

How to replace NaN values by zeroes in a column of a Python Pandas Dataframe?

Sometimes, we want to replace NaN values by zeroes in a column of a Python Pandas Dataframe.

In this article, we’ll look at how to replace NaN values by zeroes in a column of a Python Pandas Dataframe.

How to replace NaN values by zeroes in a column of a Python Pandas Dataframe?

To replace NaN values by zeroes in a column of a Python Pandas Dataframe, we can use the DataFrame’s fillna method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'col': [1, 2, 3, None, None]}).fillna(0)
print(df)

We create a DataFrame with pd.DataFrame({'col': [1, 2, 3, None, None]}).

None are the NaN values in the DataFrame.

Then we call fillna to replace None with 0 and assign the DataFrame to df.

Therefore, df is:

   col
0  1.0
1  2.0
2  3.0
3  0.0
4  0.0

Conclusion

To replace NaN values by zeroes in a column of a Python Pandas Dataframe, we can use the DataFrame’s fillna method.

Categories
Python Answers

How to create a list with a single item repeated N times with Python?

Sometimes, we want to create a list with a single item repeated N times with Python.

In this article, we’ll look at how to create a list with a single item repeated N times with Python.

How to create a list with a single item repeated N times with Python?

To create a list with a single item repeated N times with Python, we can use the * operator with a list and the number of items to repeat.

For instance, we write:

my_list = ['foo'] * 10
print(my_list)

We define my_list by using an list and 10 as an operand to return a list with 'foo' repeated 10 times.

Therefore, my_list is ['foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo'].

Conclusion

To create a list with a single item repeated N times with Python, we can use the * operator with a list and the number of items to repeat.