In this article, we will show you how to access the environment variables in Python. import os print(os.environ[‘HOME’]) print(os.getenv(‘HOME’)) P.S Tested with Python 3.9.5 1. Get an environment variable 1.1 The below code uses [os.environ(https://docs.python.org/3/library/os.html#os.environ) to print the environment variable HOME. import os print(os.environ[‘HOME’]) # /Users/mkyong 1.2 If the requested key does not exist, it […]

Read more How to get an environment variable in Python

In Python, we can use bin() or format() to convert an integer into a binary string representation. print(bin(1)) # 0b1 print(bin(-1)) # -0b1 print(bin(10)) # 0b1010 print(bin(-10)) # -0b1010 print("{0:b}".format(10)) # 1010 print("{0:#b}".format(10)) # 0b1010 , with 0b prefix print("{0:b}".format(10).zfill(8)) # 00001010 , pad zero, show 8 bits print(format(10, "b")) # 1010 print(format(10, "#b")) # […]

Read more Python – How to convert int to a binary string?

In Python, we can use index -1 to get the last element of a list. #!/usr/bin/python nums = [1, 2, 3, 4, 5] print(nums[-1]) print(nums[-2]) print(nums[-3]) print(nums[-4]) print(nums[-5]) print(nums[0]) print(nums[1]) print(nums[2]) print(nums[3]) print(nums[4]) Output 5 4 3 2 1 1 2 3 4 5 Yet another example. #!/usr/bin/python # getting list of nums from the […]

Read more Python – Get the last element of a list

Python example to read a log file, line by line into a list. # With ‘\n’, [‘1\n’, ‘2\n’, ‘3’] with open(‘/www/logs/server.log’) as f: content = f.readlines() # No ‘\n’, [‘1’, ‘2’, ‘3’] with open(‘/www/logs/server.log’) as f: content = f.read().splitlines() 1. Read File -> List 1.1 A dummy log file. d:\\server.log a b c d 1 […]

Read more Python – How to read a file into a list?

In Python, we can use in operator or str.find() to check if a String contains another String. 1. in operator name = "mkyong is learning python 123" if "python" in name: print("found python!") else: print("nothing") Output found python! 2. str.find() name = "mkyong is learning python 123" if name.find("python") != -1: print("found python!") else: print("nothing") […]

Read more Python – Check if a String contains another String?

In Python, we can use os.path.isfile() or pathlib.Path.is_file() (Python 3.4) to check if a file exists. 1. pathlib New in Python 3.4 from pathlib import Path fname = Path("c:\\test\\abc.txt") print(fname.exists()) # true print(fname.is_file()) # true print(fname.is_dir()) # false dir = Path("c:\\test\\") print(dir.exists()) # true print(dir.is_file()) # false print(dir.is_dir()) # true If check from pathlib import […]

Read more Python – How to check if a file exists

A simple Python example to print half and full pyramid, just for fun. def half_pyramid(rows): print(‘Half pyramid…\n’) for i in range(rows): print(‘*’ * (i+1)) def full_pyramid(rows): print(‘\nFull pyramid…\n’) for i in range(rows): print(‘ ‘*(rows-i-1) + ‘*’*(2*i+1)) def inverted_pyramid(rows): print(‘\nInverted pyramid…\n’) for i in reversed(range(rows)): print(‘ ‘*(rows-i-1) + ‘*’*(2*i+1)) half_pyramid(5) full_pyramid(5) inverted_pyramid(5) Output Half pyramid… * […]

Read more Python – How to print a Pyramid

In Python, you can use the in operator to check if a key exists in a dictionary. test.py def main(): fruits = { ‘apple’:1, ‘orange’:2, ‘banana’:3 } #if key ‘apple’ exists in fruits? if ‘apple’ in fruits: print(fruits[‘apple’]) if __name__ == ‘__main__’: main() Output 1 P.S Tested with Python 3.4.3 Note has_key() is deprecated in […]

Read more Python – Check if key exists in dictionary

Review a Python 2 socket example whois.py import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.arin.net", 43)) s.send(sys.argv[1] + "\r\n") #Python 2.7 send signature #socket.send(string[, flags]) If compile with Python 3, it prompts the following error? Traceback (most recent call last): File "C:\repos\hc\whois\python\whois.py", line 6, in <module> s.send(sys.argv[1] + "\r\n") TypeError: ‘str’ does not support […]

Read more Python 3 TypeError: ‘str’ does not support the buffer interface

Converting a Python 2 socket example to Python 3 whois.py import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.arin.net", 43)) s.send((sys.argv[1] + "\r\n").encode()) response = "" while True: data = s.recv(4096) response += data if not data: break s.close() print(response) If compile with Python 3, it prompts the following error? Traceback (most recent call last): […]

Read more Python 3 TypeError: Can’t convert ‘bytes’ object to str implicitly

In this example, we will show you how to read an XML file and print out its values, via Python xml.dom.minidom. 1. XML File A simple XML file, later parse it with Python minidom. staff.xml <?xml version="1.0"?> <company> <name>Mkyong Enterprise</name> <staff id="1001"> <nickname>mkyong</nickname> <salary>100,000</salary> </staff> <staff id="1002"> <nickname>yflow</nickname> <salary>200,000</salary> </staff> <staff id="1003"> <nickname>alex</nickname> <salary>20,000</salary> </staff> […]

Read more Python – Read XML file (DOM Example)

Here is an email example written in Python module “smtplib”. It will connect to the GMail SMTP server and do the authentication with username and password given (hardcoded in program), and use the GMail SMTP server to send email to the recipient. import smtplib to = ‘[email protected]’ gmail_user = ‘[email protected]’ gmail_pwd = ‘yourpassword’ smtpserver = […]

Read more How to send email in Python via SMTPLIB