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()

沒有留言:

Powered By Blogger