PythonNotes

From DiLab
Revision as of 16:50, 19 June 2009 by Girts (talk | contribs) (New page: Šeit pierakstu lietas, ko iemācos pa ceļam, apgūstot [http://www.python.org/ Python] ar Gūgles palīdzību - kad kaut ko vajag izdarīt, meklēju vajadzīgās funkcijas/paņēmienus. ...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Šeit pierakstu lietas, ko iemācos pa ceļam, apgūstot Python ar Gūgles palīdzību - kad kaut ko vajag izdarīt, meklēju vajadzīgās funkcijas/paņēmienus.

2009-06-19

Hello world

print "Hello, world";

Main function

if __name__ == '__main__':
    print "Hello world";

Script execution

python yourscript.py

Get local timestamp

import time
print time.time()

Type casting

Type casting functions: int(), str(), list(), tuple(), dict().

a = 1.5
print int(a)
print str(a)

Print with several arguments

Type all arguments to strings, concatenate them:

a = 5
print "this is an int: " + str(a)

Convert decimal to hexadecimal

print hex(67)

Get ASCII code of a character

print ord('A')

Reading/writing files

f = open("myfile.txt", "r")
contents = f.read()  // read the whole file
bytes5 = f.read(5) // read 5 bytes
outfile = open("output.txt", "w");
outfile.write("abc def");
f.close()
outfile.close()

Store/load variable to/from file

import pickle

t = [1, 3, 5]
f = open("myfile.txt", "w")
pickle.dump(f, t)
// ...

t = pickle.load(f)

Replace substring

s = "Hello, world!"
print s.replace("world", "python");

Split string by delimiter

a = "1;2;3"
print a.split(";")