Python programming

From Got Opinion Wiki
Jump to navigation Jump to search

Python basics

Python IDE

In 2016 I started using PyCharm by JetBrains for Python IDE. JetBrains has a Community Edition version which is free.

Before PyCharm I used PyDev for my Python IDE. See My PyDev Notes section.

Escape sequences

Insert list or link to list of escape sequences

Type conversions

int() float()

Python string formatting

A nice collection of new and old Python format examples. I should really add some examples as this site has helped me out more than a few times. I like the examples and style used by the site.

Format String Syntax

Format Specification Mini-Language

time.strftime and use %f to get microseconds

Conditionals

Operator Conditions when true
x == y x and y have same value
x != y x and y don't have same value
x < y x value is less than y value
x <= y x value is less than or equal to y value
x > y x value is greater than y value
x >= y x value is greater than or equal to y value


string methods (s1 and s2 are strings) conditions when true
s1.startswith(s2) String s1 starts with s2
s1.endswith(s2) String s1 ends with s2
s1.isalnum() All characters in s1 are alphanumeric and there is >= 1 character
s1.isalpha() All characters in s1 are alphabetic and there is >= 1 character
s1.isdigit() All characters in s1 are digits and there is >= 1 character
s1.islower() All cased characters in s1 are lowercase and there is >= 1 cased character
s.isupper() All cased characters in s1 are uppercase and there is >= 1 cased character

Lists, Tuples, Sets, Dicts

to do :: List operations you can perform on each...in a chart...


Sets // fill in later

Operation Method Call Returns

Python operators

Loops

While loop

How to exit while loop using Enter key

while True:
    i = input("Enter text (or Enter to quit): ")
    if not i:
        break
    print("Your input:", i)
print("While loop has exited")


For loop

How to cycle through elements viewing each one by pressing Enter key or any character to exit

for element_in_list in big_list:
    if not input("Press Enter to see next item or any other character to exit: "):
        print(element_in_list)
    else:
        break

Python datetime module

datetime module supplies classes for manipulating dates and times in both simple and complex ways.

strftime and strptime behavior

HOWTO get an ISO 8601 or ASN.1 GeneralizedTime time format out of Python datetime object

>>> datetime.MINYEAR		  
1
>>> datetime.MAXYEAR
		  
9999

>>> datetime.datetime.now()
		  
datetime.datetime(2019, 3, 31, 21, 29, 47, 993877)
>>> from datetime import datetime
		  
>>> datetime.now()
		  
datetime.datetime(2019, 3, 31, 21, 30, 4, 999219)
>>> d = datetime.now()
		  
>>> d
		  
datetime.datetime(2019, 3, 31, 21, 30, 51, 362520)
>>> f = '{:%Y%m%d%H%M%S.%f}'  < -- Setup a string format to control the datetime format.
		  
>>> f.format(d)
		  
'20190331213051.362520' < -- microsecond accuracy
>>> d2 = datetime(2019, 3, 31, 21, 30, 51, 000000)  < -- Create datetime object with exactly zero microseconds to verify string format.
		  
>>> f.format(d2)
		  
'20190331213051.000000' < -- verified that datetime displays six zeros
>>> '20190331213051.000000'[:-3] < -- truncate last three digits
		  
'20190331213051.000' < -- Now we need timezone offset
>>> z = datetime.datetime.utcnow() < -- I want UTC time so I use datetime class method utcnow()
		  
>>> z
		  
datetime.datetime(2019, 4, 1, 3, 28, 53, 152240) < -- not in format I want
>>> f.format(z) < -- apply format specification used above
		  
'20190401032853.152240' < -- want to remove least 3 insignificant digits from microseconds
>>> f.format(z)[:-3]
		  
'20190401032853.152' < -- missing offset
>>> f.format(z)[:-3]+'Z' < -- simple string concatenate
		  
'20190401032853.152Z' < -- final product

Summary of string formatting to get to ISO 8601 from Python datetime object

  • Format string: '{:%Y%m%d%H%M%S.%f}'
  • Truncate last three digits from formatted string: [:-3]
  • Concatenate 'Z' for Zulu time + 'Z'

Complete example (without references)

>>> '{:%Y%m%d%H%M%S.%f}'.format(datetime.datetime.utcnow())[:-3] + 'Z'
							  
'20190401034018.177Z'

Working with JSON in Python

Working With JSON Data in Python by Lucas Lofaro

Python Network Programming

My Python Network Programming Notes

Converting binary string and text string

The binascii module contains a number of methods to convert between binary and various ASCII-encoded binary representations.

>>> import binascii

>>> b = binascii.hexlify(b'binary_string') < -- convert from binary string to binary hexadecimal representation...similar to bytes.hex() except this returns binary string
							  
>>> b
							  
b'62696e6172795f737472696e67' < -- binary hexadecimal representation
>>> binascii.a2b_hex(b) <-- convert from binary hexadecimal to binary string
							  
b'binary_string'

>>> bytes.hex(b) < -- convert binary hexadecimal b'62696e6172795f737472696e67' to octet strings (takes up twice as much space)
							  
'3632363936653631373237393566373337343732363936653637'

>>> s = '1234567890'  < -- create sample string
							  
>>> bo = bytes(s, 'ascii') < -- create bytes object of string (binary string)
							  
>>> bo
							  
b'1234567890' < -- notice the little b in front of the first single quote
>>> octet_string = bytes.hex(bo)  < -- convert bytes object (binary string) to octet string
							  
>>> octet_string
							  
'31323334353637383930'

Converting back and forth with binascii and bytes

>>> import datetime

>>> dt = datetime.datetime.utcnow()

>>> dt
datetime.datetime(2019, 4, 2, 1, 36, 8, 931977)

>>> f = '{:%Y%m%d%H%M%S.%f}'

>>> f.format(dt)
'20190402013608.931977'

>>> f.format(dt)[:-3]+'Z'
'20190402013608.931Z'

>>> t = f.format(dt)[:-3]+'Z'

>>> t
'20190402013608.931Z'

>>> bytes(t,'ascii')
b'20190402013608.931Z'

>>> binascii.hexlify(bytes(t,'ascii'))
b'32303139303430323031333630382e3933315a'

>>> binascii.hexlify(bytes(t,'ascii'))
b'32303139303430323031333630382e3933315a'

>>> bt = binascii.hexlify(bytes(t,'ascii'))

>>> bt
b'32303139303430323031333630382e3933315a'

>>> bt.decode()
'32303139303430323031333630382e3933315a'

>>> '32303139303430323031333630382e3933315a'.encode()
b'32303139303430323031333630382e3933315a'

>>> b'32303139303430323031333630382e3933315a'.decode()
'32303139303430323031333630382e3933315a'

Miscellaneous stuff

Difference Between Carriage Return, Line Feed and End of Line Characters

To Python