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

l = [s + my_string for s in my_list]

to append my_string to the end of each string s in the my_list list.

And then we return the values in a new list.

Conclusion

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

Categories
Python Answers

How to write a Python dictionary to a csv file?

Sometimes, we want to write a Python dictionary to a csv file.

In this article, we’ll look at how to write a Python dictionary to a csv file.

How to write a Python dictionary to a csv file?

To write a Python dictionary to a csv file, we can use the csv.DictWriter class.

For instance, we write

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

to call open to open mycsvfile.csv with write permission.

Then we create the DictWriter object with the file f and the keys of my_dict as column names.

Then we call writeheader to write the column name as headers.

And then we call writerow to write the my_dict dict’s values as a row.

Conclusion

To write a Python dictionary to a csv file, we can use the csv.DictWriter class.

Categories
Python Answers

How to run an external command asynchronously from Python?

Sometimes, we want to run an external command asynchronously from Python.

In this article, we’ll look at how to run an external command asynchronously from Python.

How to run an external command asynchronously from Python?

To run an external command asynchronously from Python, we can use the asyncio.create_subprocess_exec method.

For instance, we write

import asyncio

proc = await asyncio.create_subprocess_exec(
   'ls','-lha',
   stdout=asyncio.subprocess.PIPE,
   stderr=asyncio.subprocess.PIPE)

stdout, stderr = await proc.communicate()

to run a process asynchronously with asyncio.create_subprocess_exec.

We call it with the command and command arguments strings.

And we set stdout and stderr to asyncio.subprocess.PIPE to pipe the results so that we can get their values with proc.communicate.

Using await will keep the code from blocking the CPU from running something else.

Conclusion

To run an external command asynchronously from Python, we can use the asyncio.create_subprocess_exec method.

Categories
Python Answers

How to pass data from Flask to JavaScript in a template?

Sometimes, we want to pass data from Flask to JavaScript in a template.

In this article, we’ll look at how to pass data from Flask to JavaScript in a template.

How to pass data from Flask to JavaScript in a template?

To pass data from Flask to JavaScript in a template, we can interpolate variables in the template.

For instance, we write

<html>
  <head>
    <script>
      let myGeocode = ['{{ geocode[0] }}', '{{ geocode[1] }}'];
    </script>
  </head>
  <body>
    <p>Hello World</p>
    <button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
  </body>
</html>

to add the template with the geocode array values interpolated into the template.

We can use the tojson filter to convert JSON strings into JavaScript objects.

For instance, we write

<html>
  <head>
    <script>
      let myGeocode = {{ geocode|tojson }};
    </script>
  </head>
  <body>
    <p>Hello World</p>
    <button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
  </body>
</html>

to use the tojson filter to parse the geocode variable into a JavaScript object.

Conclusion

To pass data from Flask to JavaScript in a template, we can interpolate variables in the template.

Categories
Python Answers

How to validate IP address in Python?

Sometimes, we want to validate IP address in Python.

In this article, we’ll look at how to validate IP address in Python.

How to validate IP address in Python?

To validate IP address in Python, we can use the ipaddress library.

To install it, we run

pip install ipaddress

Then we use it by writing


import ipaddress

# ...

try:
    ip = ipaddress.ip_address(ip_address)
    print(ip, ip.version)
except ValueError:
    print('invalid ip')

to call ipaddress.ip_address to try to parse the ip_address string.

If it’s successful, then we get the IP address from the ip object.

And we get the IP address version from ip.version.

Otherwise, a ValueError will be thrown.

Conclusion

To validate IP address in Python, we can use the ipaddress library.