顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

2009年3月11日 星期三

Python Built-in Types

Built-in Types

Numeric — int, long, float, complex
type
description
int
plain integers
long
long integers
float
floating point numbers, here is some additional methods
complex
complex numbers. To extract these parts from a complex number z, use z.real and z.imag.


Sequence Types — str, unicode, list, tuple, buffer, xrange
type
description
strstrings. Some methods are listed below, or read String Method for more infomation.
unicodeUnicode strings. much like strings, but are specified in the syntax using a preceding 'u' character: u'abc', u"def".
listlists, constructed with square brackets, separating items with commas.
tupletuples, constructed without square brackets, separating items with commas
bufferbuffers, not directly supported by Python syntax. read buffer() to get details
xrangexrange objects, similar to buffers. read xrange() to get details


String objects
#Return a string with first character capitalized.
#similar to css text-transform
str.capitalize()
str.lower()
str.upper()
str.swapcase()

#get the first index of the substring
str.find(sub[, start[, end]])
# similar to find(), but raise ValueError if not found.
str.index(sub[, start[, end]])
#search from the end to the start
str.rfind(sub[, start[, end]])
str.rindex(sub[, start[, end]])

#replace the old substring with the new substring
str.replace(old, new[, count])

#split the string with separator
str.split([sep[, maxsplit]])
str.splitlines([keepends])
str.rsplit([sep[, maxsplit]])

#remove the leading and trailing characters
#you can specify characters to remove from the leading and trailing
str.strip([chars])

Extended read: String Formatting Operations

Lists objects
Fredrik Lundh - An Introduction to Python Lists
#To create a list
L = []
#OR
L = list()

#To get the length of an unknown size array
n = len(L)

#Add items to list
L.append(item)
L.extend(sequence)
L.insert(index, item)

#Sort the list
L.sort()

Extended read: Mutable Sequence Types

File Objects
#open the file, similar fopen in C
file = open(filename[, mode[, bufsize]])

#read the file
file.read([size])
file.readline([size])
file.readlines([size])

#write to file
file.write(str)
file.writelines(sequence)

#close the tile
file.close()

Python Time and date

PLEAC-Python : Dates and Times
#python
import time
import datetime

#only date
today = datetime.date.today()

#now time, including date and time
now = datetime.datetime.now()

#UTC now time, including date and time
utcnow = datetime.datetime.utcnow()

#ctime() standard time output string
print now.ctime()
#Thu Feb 26 17:50:55 2009

#strftime() (string-format time) format the output string
print now.strftime("%A %B %d %I:%M:%S %p %Y")
#Thursday Febuary 14 05:50:55 PM 2009


For more example, please read Dates and Times
datetime — Basic date and time types
Powered By Blogger