Categories
Python Answers

How to display a float with two decimal places with Python?

Sometimes, we want to display a float with two decimal places with Python.

In this article, we’ll look at how to display a float with two decimal places with Python.

How to display a float with two decimal places with Python?

To display a float with two decimal places with Python, we can use the string’s format method.

For instance, we write:

n = "{:.2f}".format(5)
print(n)

We call format on "{:.2f}" with a number to render the number 5 with 2 decimal places.

Therefore, n is 5.00.

Conclusion

To display a float with two decimal places with Python, we can use the string’s format method.

Categories
Python Answers

How to get permutations between two lists of unequal length with Python?

Sometimes, we want to to get permutations between two lists of unequal length with Python.

In this article, we’ll look at how to get permutations between two lists of unequal length with Python.

How to get permutations between two lists of unequal length with Python?

To get permutations between two lists of unequal length with Python, we can use the itertools.product method.

For instance, we write:

import itertools
from pprint import pprint

inputdata = [
    ['a', 'b', 'c'],
    ['d'],
    ['e', 'f'],
]
result = list(itertools.product(*inputdata))
pprint(result)

We call itertools.product with the lists unpacked from inputdata.

Then we call list on the returned iterable to convert it to a list and assign the returned list to result.

Therefore, result is:

[('a', 'd', 'e'),
 ('a', 'd', 'f'),
 ('b', 'd', 'e'),
 ('b', 'd', 'f'),
 ('c', 'd', 'e'),
 ('c', 'd', 'f')]

Conclusion

To get permutations between two lists of unequal length with Python, we can use the itertools.product method.

Categories
Python Answers

How to split a list into N parts of approximately equal length with Python?

Sometimes, we want to split a list into N parts of approximately equal length with Python.

In this article, we’ll look at how to split a list into N parts of approximately equal length with Python.

How to split a list into N parts of approximately equal length with Python?

To split a list into N parts of approximately equal length with Python, we can use list comprehension.

For instance, we write:

def chunkify(lst, n):
    return [lst[i::n] for i in range(n)]


chunks = chunkify(list(range(13)), 3)
print(chunks)

We define the chunkify function to split the lst list into n chunks.

To do this, we use list comprehension to return slices of list with from index i to the end with n items in each chunk.

Then we call chunkify with the list(range(13)) list and 3 to divide the list into 3 chunks.

Therefore, chunks is [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]].

Conclusion

To split a list into N parts of approximately equal length with Python, we can use list comprehension.

Categories
Python Answers

How to get a directory listing sorted by creation date in Python?

Sometimes, we want to get a directory listing sorted by creation date in Python.

In this article, we’ll look at how to get a directory listing sorted by creation date in Python.

How to get a directory listing sorted by creation date in Python?

To get a directory listing sorted by creation date in Python, we can use the pathlib module.

For instance, we write:

import os
from pathlib import Path

dirpath = '/'
paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)
print(paths)

We get the directories within dirpath with Path(dirpath).iterdir().

And we call sorted with Path(dirpath).iterdir() and key to os.path.getmtime sort by time modified.

Finally, we assign the returned list of path objects to paths.

Therefore, paths is something like:

[PosixPath('/boot'), PosixPath('/media'), PosixPath('/srv'), PosixPath('/lib64'), PosixPath('/var'), PosixPath('/home'), PosixPath('/root'), PosixPath('/sbin'), PosixPath('/lib32'), PosixPath('/gocode'), PosixPath('/run_dir'), PosixPath('/phase2-erlang.tar.bz2'), PosixPath('/phase2-jest.tar.bz2'), PosixPath('/phase2-d.tar.bz2'), PosixPath('/phase2-mercury.tar.bz2'), PosixPath('/phase2-express.tar.bz2'), PosixPath('/phase2-php.tar.bz2'), PosixPath('/phase2-guile.tar.bz2'), PosixPath('/phase2-csharp.tar.bz2'), PosixPath('/phase2-fortran.tar.bz2'), PosixPath('/phase2-fsharp.tar.bz2'), PosixPath('/phase2-rlang.tar.bz2'), PosixPath('/phase2-cpp.tar.bz2'), PosixPath('/phase2-assembly.tar.bz2'), PosixPath('/phase2-crystal.tar.bz2'), PosixPath('/phase2-pascal.tar.bz2'), PosixPath('/phase2-prolog.tar.bz2'), PosixPath('/phase2-haskell.tar.bz2'), PosixPath('/phase2-clisp.tar.bz2'), PosixPath('/phase2-love2d.tar.bz2'), PosixPath('/phase2-elixir.tar.bz2'), PosixPath('/phase2-cpp11.tar.bz2'), PosixPath('/phase2-react_native.tar.bz2'), PosixPath('/bin'), PosixPath('/lib'), PosixPath('/usr'), PosixPath('/opt'), PosixPath('/mnt'), PosixPath('/inject'), PosixPath('/io'), PosixPath('/etc'), PosixPath('/.dockerenv'), PosixPath('/sys'), PosixPath('/proc'), PosixPath('/dev'), PosixPath('/config'), PosixPath('/nix'), PosixPath('/run'), PosixPath('/tmp')]

Conclusion

To get a directory listing sorted by creation date in Python, we can use the pathlib module.

Categories
Python Answers

How to change the user agent header with Python urllib?

Sometimes, we want to change the user agent header with Python urllib.

In this article, we’ll look at how to change the user agent header with Python urllib.

How to change the user agent header with Python urllib?

To change the user agent header with Python urllib, we can call the build_opener method.

Then we set the addheaders attribute of the returned object to add the user-agent request header.

For instance, we write:

import urllib.request

opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.example.com')
print(response)

We call urllib.request.build_opener method and assign the returned object to opener.

Then we set opener.addheaders attribute to [('User-Agent', 'Mozilla/5.0')] to set the user-agent header to Mozilla/5.0.

Next, we call opener.open with the URL we want to make a GET request to and assign the returned response to response.

Finally, we print the response.

Conclusion

To change the user agent header with Python urllib, we can call the build_opener method.

Then we set the addheaders attribute of the returned object to add the user-agent request header.