How to get an environment variable in Python

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 read a file in Python

This article shows how to read a text file in Python. Table of contents 1. Read a file using open() and close() 2. Read a file using with statement 3. Read a file using try-finally 4. Read a file line by line 5. Read a file and skip the first line 6. Default open mode …

Read more

How to reverse a string in Python

In Python, the fastest and easiest way to reverse a string is the extended slice, [::-1]. print("hello world"[::-1]) # dlrow olleh This article will show you a few ways to reverse a string in Python. [::-1] reverse order slice. (Good) [::-1] slice implement as function. (Good) Reversed and Join (Reverse String and Words) (Ok) Python …

Read more

Python – How to convert int to a binary string?

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 MD5 Hashing Example

The MD5, defined in RFC 1321, is a hash algorithm to turn inputs into a fixed 128-bit (16 bytes) length of the hash value. Note MD5 is not collision-resistant – Two different inputs may producing the same hash value. Read this MD5 vulnerabilities. In Python, we can use hashlib.md5() to generate a MD5 hash value …

Read more

Python – How to split string into a dict

Few Python examples to show you how to split a string into a dictionary. 1.1 Split a string into a dict. #!/usr/bin/python str = "key1=value1;key2=value2;key3=value3" d = dict(x.split("=") for x in str.split(";")) for k, v in d.items(): print(k, v) Output key1 value1 key2 value2 key3 value3 1.2 Convert two list into a dict. #!/usr/bin/python str1 …

Read more

Python Ternary Conditional Operator

This article shows you how to write Python ternary operator, also called conditional expressions. <expression1> if <condition> else <expression2> expression1 will be evaluated if the condition is true, otherwise expression2 will be evaluated. 1. Ternary Operator 1.1 This example will print whether a number is odd or even. n = 5 print("Even") if n % …

Read more

Python – Get the last element of a list

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 – How to trim a String?

In Python trim method is called strip, it removes the leading and trailing spaces of a String. str.strip() #trim str.lstrip() #ltrim str.rstrip() #rtrim #!/usr/bin/python str = " abc " print(str) print(str.strip()) print(str.lstrip()) print(str.rstrip()) Output {space} abc {space} abc abc {space} {space} abc References Python docs str.strip()

Python – How to print dictionary

Python example to print the key value of a dictionary. stocks = { ‘IBM’: 146.48, ‘MSFT’: 44.11, ‘CSCO’: 25.54 } print(stocks) for k, v in stocks.items(): print(k, v) for k in stocks: print(k, stocks[k]) Output {‘IBM’: 146.48, ‘MSFT’: 44.11, ‘CSCO’: 25.54} IBM 146.48 MSFT 44.11 CSCO 25.54 IBM 146.48 MSFT 44.11 CSCO 25.54 References Python …

Read more

Python – How to read a file into 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 – Check if a String contains another String?

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 – How to check if a file exists

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 convert String to float

In Python, we can use float() to convert String to float. num = "3.1415" print(num) print(type(num)) # str pi = float(num) # convert str to float print(pi) print(type(pi)) # float Output 3.1415 <class ‘str’> 3.1415 <class ‘float’> References Python docs – float()

Python – How to convert int to String

In Python, we can use str() to convert a int to String. num1 = 100 print(type(num1)) # <class ‘int’> num2 = str(num1) print(type(num2)) # <class ‘str’> Output <class ‘int’> <class ‘str’> References Python docs – str() Python – How to convert String to int

Python – How to convert String to int

In Python, we can use int() to convert a String to int. # String num1 = "88" # <class ‘str’> print(type(num1)) # int num2 = int(num1) # <class ‘int’> print(type(num2)) 1. Example A Python example to add two numbers. 1.1 Add two String directly. num1 = "1" num2 = "2" num3 = num1 + num2 …

Read more

Python – How to convert float to String

In Python, we can use str() to convert float to String. pi = 3.1415 print(type(pi)) # float piInString = str(pi) # float -> str print(type(piInString)) # str Output <class ‘float’> <class ‘str’> References Python docs – str() Python – How to convert int to String Python – How to convert String to float

Python – How to print a Pyramid

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 join two list

In Python, you can simply join two list with a plus + symbol like this: list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 print list3 #[1, 2, 3, 4, 5, 6] Note Try to compare with this Java example – how to join arrays. Python really makes join list extremely easy.

Python – How to split a String

Few examples to show you how to split a String into a List in Python. 1. Split by whitespace By default, split() takes whitespace as the delimiter. alphabet = "a b c d e f g" data = alphabet.split() #split string into a list for temp in data: print temp Output a b c d …

Read more

Python – How to loop a List

In this tutorial, we will show you how to use for-in-loop to loop a List in Python. #example 1 frameworks = [‘flask’, ‘pyramid’, ‘django’] #list for temp in frameworks: print temp print "Python framework : %s" %temp #example 2 numbers = [2,4,6,8,10] #list for num in numbers: print num print "Number : %d" %num Output …

Read more

Python – How to delay few seconds

In Python, you can use time.sleep(seconds) to make the current executing Python program to sleep or delay a few seconds. import time time.sleep(1) # delays for 1 seconds time.sleep(10) # delays for 10 seconds time.sleep(60) # delays for 1 minute time.sleep(3600) # delays for 1 hour Full example. test_delay.py import time def main(): while True: …

Read more

Python – How to loop a dictionary

In this tutorial, we will show you how to loop a dictionary in Python. 1. for key in dict: 1.1 To loop all the keys from a dictionary – for k in dict: for k in dict: print(k) 1.2 To loop every key and value from a dictionary – for k, v in dict.items(): for …

Read more

Python Whois client example

In this article, we will show you how to create a simple Whois client both in Python 2 and Python 3. Tested Python 2.7.10 Python 3.4.3 1. Python 3 Whois example In Python 3, the socket accepts bytes, so you need to encode() and decode() manually. whois3.py import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) …

Read more

Python – Check if key exists in dictionary

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 3 TypeError: ‘str’ does not support the buffer interface

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: Can’t convert ‘bytes’ object to str implicitly

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 : Convert string to bytes

Code snippets to show you how to convert string to bytes and vice versa. 1. To convert a string to bytes. data = "" #string data = "".encode() #bytes data = b"" #bytes 2. To convert bytes to a String. data = b"" #bytes data = b"".decode() #string data = str(b"") #string P.S Tested with …

Read more

Python – Read XML file (DOM Example)

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

How to send email in Python via SMTPLIB

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