Appendices
Several special characters have backslash versions:
| Backslash Representation | Character |
\t
| Tab |
\v
| Vertical-Tab |
\n
| New-Line |
\r
| Return |
\f
| Form-Feed |
\"
| Quote |
\'
| Apostrophe |
\\
| Backslash |
\b
| Backspace |
\a
| Bell |
\000
| Octal value (3 base-8 digits in range 0-3778) |
\xXX...
| Hex value (2 base 16-digits in range 0-FF16) used in strings (that is, "\x31" --> '1') |
\uXXXX...
| Hex value (4 base 16-digits in range 0-FFFF16); used in unicode strings (that is, u"\u0031" --> '1') |
Strings support several useful methods:
| Method | Usage | Example |
s.capitalize()
| Initial capitalize s | "abc".capitalize() --> "Abc" |
s.count(ss {,start {,end}})
| Count the occurrences of ss in s[start:end] | "aaabbccc".count("ab") --> 1 |
s.startswith(str {, start {, end}})
s.endswith(str {, start {, end}}) | Test to see if s starts/ends with str | "xxxyyyzzz".startswith("xx") --> 1 |
s.expandtabs({size})
| Replace tabs with spaces, default size: 8 | "x\ty".expandtabs(4) --> "x y" |
s.find(str {, start {, end}})
s.rfind(str {, start {, end}})
| Finds first index of str in s; if not found: -1, rfind searches right-to-left | "12345".find('23') --> 1 |
s.index(str {, start {, end}})
s.rindex(str {, start {, end}})
| Finds first index of str in s; if not found: raise ValueError. rindex searches right-to-left | "12345".index('23') --> 1 |
s.isalnum
| Test to see if the string is alphanumeric | "12345abc".isalnum() --> 1 |
s.isalpha
| Test to see if the string is alphabetic | "12345abc".isalpha() --> 0 |
s.isnum
| Test to see if the string is numeric | "12345abc".isnum() --> 0 |
s.isupper
| Test to see if the string is all uppercase | "abc".isupper() --> 0 |
s.islower
| Test to see if the string is all lowercase | "abc".islower() --> 1 |
s.isspace
| Test to see if the string is all whitespace | "12345 abc".isspace() --> 0 |
s.istitle
| Test to see if the string is a sequence of initial cap alphanumeric strings | "Abc Pqr".istitle() --> 1 |
s.lower()
s.upper()
s.swapcase()
s.title()
| Convert to all lower, upper, opposite, or title case |
"abcXYZ".lower() --> "abcxyz"
"abc def ghi".title() --> "Abc Def Ghi" |
s.join(seq)
| Join the strings in seq with s as the separator | " ".join(("hello", "goodbye") --> "hello goodbye" |
s.splitlines({keep})
| Split s into lines, if keep true, keep the newlines | "one\ntwo\nthree".splitlines() --> ["one", "two", "three"] |
s.split({sep {, max}})
| Split s into "words" using sep (default of white space) for up to max times | "one two three".split() --> ["one", "two", "three"] |
s.ljust(width)
s.rjust(width)
s.center(width)
s.zfill(width)
| Left, right or center justify the string in a field width wide. Fill with 0. |
"xxx".rjust(8) --> " xxx"
"xxx".center(8) --> " xxx " str(10).zfill(10) --> "0000000010" |
s.lstrip()
s.rstrip()
s.strip()
| Remove leading (and/or trailing) white space | " xxx ".strip() --> "xxx" |
s.translate(str {,delc})
| Translate s using table, after removing any characters in delc. str should be a string with length == 256 | "ab12c".translate(reversealpha, "0123456789") --> "cba" |
s.replace(old, new {, max})
| Replaces all or max occurrences old string old with string new | "11111".replace('1', 'a', 2) --> "aa111" |
Note: other methods are supported,
for a complete list see the Python Library Reference (Resources).
Also note that by including the string module, many (but not all) of
these methods can also be called
as functions, i.e.- string.center(s, 10) is the same as
s.center(10).
The string module has some important variables:
| Variable | Comment(s) |
|
digits
octdigits hexdigits | The decimal, octal, and hexadecimal digits |
|
lowercase
uppercase letters | The lowercase alphabet, the uppercase alphabet, and the union of them |
| whitespace | The legal white space characters |
Lists support several useful methods.
| Function | Comment(s) | Example |
|
x in l
x not in l | Test for containment | 1 in [1,2,3,4] --> 1 |
| l.count(x) | Count the occurrences of x. Uses "==" to test. | [1,2,3,3].count(3) --> 2 |
|
l.append(x)
-- or -- l = l + [x] | Append x to the list |
[1,2].append([3,4]) --> [1,2,[3,4]]
[1,2] + [3] --> [1,2,3] |
| l.extend(list) | Appends the elements of list | [1,2].extend([3,4]) --> [1,2,3,4] |
| l.index(item) | Finds the index of item in list; if not present, raise ValueError | [1,2,3,4].index(3) --> 2 |
|
l.insert(index, x)
-- or -- l[i:i] = [x] | Insert x into the list before the index | [1,2,3].insert(1, 4) --> [1,4,2,3] |
| l.pop({index}) | Removes the nth (default last) item |
[1,2,3,4].pop(0) --> [2,3,4], 1
[1,2,3,4].pop() --> [1,2,3], 4 |
| l.remove(x) | Removes the item from the list | [1,2,3,4].remove(3) --> [1,2,4] |
| l.reverse() | Reverses the list (in-place) | [1,2,3].reverse() --> [3,2,1] |
| l.sort({cmp}) | Sorts the list (in-place); The cmp function is used to sort the items. The cmp function takes two argument and returns <0, 0, >0 | [1,4,3,2].sort() --> [1,2,3,4] |
Maps support several useful methods.
| Method | Comment(s) | |
| m.clear() | Empty the map | |
| m.copy() | Make a shallow copy of the map | |
|
m.has_key(k)
-- or -- k in m | Test to see if a key is present | |
| m.items() | Get a list of the key/value tuples | |
| m.keys() | Get a list of the keys | |
| m.values() | Get a list of the values (may have duplicates) | |
| m1.update(m2) | add all the items in m2 to m1 | |
|
m.get(k{, default})
m.setdefault(k, default) | Get the value of k, return default/KeyError if missing; same as get, but set a persistent default value | |
| m.popitem() |
Get and remove some item, used during iteration over the map.
Example:
|
Appendix E: Built-in functions
Jython provides very useful built-in functions that can be used without any imports. The most commonly used ones are summarized below:
| Syntax | Use/Comment(s) | Example(s) | |
| abs(x) | Absolute value | abs(-1) --> 1 | |
|
apply(func, pargs {, kargs})
-- or -- func(*pargs {, **kargs}) | Execute the function with the supplied positional arguments and optional keyword arguments | apply(lambda x, y: x * y, (10, 20)) --> 200 | |
| callable(x) | Tests to see if the object is callable (i.e, is a function, class or implements __call__) | callable(MyClass) --> 1 | |
| chr(x) | Converts the integer (0 - 65535) to a 1-character string | chr(9) --> "\t" | |
| cmp(x, y) | Compares x to y: returns: negative if x < y; 0 if x == y; positive if x > y | cmp("Hello", "Goodbye") --> > 0 | |
| coerce(x, y) | Returns the tuple of x and y coerced to a common type | coerce(-1, 10.2) --> (-1.0, 10.2) | |
| compile(text, name, kind) | Compile the text string from the source name. Kind is: "exec", "eval" or "single" |
| |
| complex(r, i) | Create a complex number |
complex(1, 2) --> 1.0+2.0j
complex("1.0-0.1j") --> 1.0-0.1j | |
| dir({namespace}) | Returns a list of the keys in a namespace (local if omitted) | dir() --> [n1, ..., nN] | |
| vars({namespace}) | Returns the namespace (local if omitted); do not change it | vars() --> {n1:v1, ..., nN:vN} | |
| divmod(x, y) | Returns the tuple (x /y, x % y) | divmod(100, 33) --> (3, 1) | |
| eval(expr {, globals {, locals}}) | Evaluate the expression in the supplied namespaces |
| |
| execfile(name {,globals {, locals}}) | Read and execute the named file in the supplied namespaces | execfile("myfile.py") | |
| filter(func, list) | Creates a list of items for which func returns true | filter(lambda x: x > 0, [-1, 0, 1, -5, 10]) --> [1, 10] | |
| float(x) | Converts x to a float |
float(10) --> 10.0
float("10.3") --> 10.3 | |
| getattr(object, name {, default}) | Gets the value of the object's attribute; if not defined return default (or an exception if no default) | getattr(myObj, "size", 0) --> 0 | |
| setattr(object, name, value) | Creates/sets the value of the object's attribute | setattr(myObj, "size", 10) | |
| hasattr(object, name) | Test to see if the object has an attribute | hasattr(myObj, "size") --> 0 | |
| globals() | Returns the current global namespace dictionary | {n1:v1, ..., nN:vN} | |
| locals() | Returns the current local namespace dictionary | {n1:v1, ..., nN:vN} | |
| hash(object) |
Returns the object's hash value.
Similar to java.lang.Object.hashCode()
| hash(x) --> 10030939 | |
| hex(x) | Returns a hex string of x | hex(-2) --> "FFFFFFFE" | |
| id(object) | Returns a unique stable integer id for the object | id(myObj) --> 39839888 | |
| input(prompt) |
Prompts and evaluates the supplied input expression;
equivalent to eval(raw_input(prompt))
|
input("Enter expression:")
with "1 + 2" --> 3 | |
| raw_input(prompt) | Prompts for and inputs a string |
raw_input("Enter value:")
with "1 + 2" --> "1 + 2" | |
| int(x{, radix}) | Converts to an integer; radix: 0, 2..36; 0 implies guess |
int(10.2) --> 10
int("10") --> 10 int("1ff", 16) --> 511 | |
| isinstance(object, class) | Tests to see if object is an instance of class or a subclass of class; class may be a tuple of classes to test multiple types |
isinstance(myObj, MyObject) --> 0
isinstance(x, (Class1, Class2)) --> 1 | |
| issubclass(xclass, clsss) | Tests to see if xclass is a sub-(or same) class of class; class may be a tuple of classes to test multiple types | issubclass(MyObject, (Class1, Class2)) --> 0 | |
| len(x) | Returns the length (number of items) in the sequence or map | len("Hello") --> 5 | |
| list(seq) | Converts the sequence into a list |
list((1, 2, 3)) --> [1,2,3]
list("Hello") --> ['H','e','l','l','o'] | |
| tuple(seq) | Converts the sequence into a tuple | tuple((1, 2, 3)) --> (1,2,3) tuple("Hello")--> ('H','e','l','l','o') | |
| long(x {, radix}) | Converts to a long integer; radix: 0, 2..36; 0 implies guess |
long(10) --> 10L
long("10000000000") --> 10000000000L | |
| map(func, list, ...) | Creates a new list from the results of applying func to each element of each list |
map(lambda x,y: x+y, [1,2],[3,4]) --> [4,6]
map(None, [1,2],[3,4]) --> [[1,3],[2,4]] | |
| max(x) | Returns the maximum value |
max(1,2,3) --> 3
max([1,2,3]) --> 3 | |
| min(x) | Returns the minimum value |
min(1,2,3) --> 1
min([1,2,3]) --> 1 | |
| oct(x) | Converts to an octal string |
oct(10) --> "012
oct(-1) --> "037777777777" | |
| open(name, mode {, bufsize}) | Returns an open file. Mode is:(r|w|a){+}{b} | open("useful.dat", "wb", 2048) | |
| ord(x) | Returns the integer value of the character | ord('\t') --> 9 | |
|
pow(x,y)
pow(x,y,z) |
Computes x ** y
Computes x ** y % z | pow(2,3) --> 8 | |
|
range({start,} stop {, inc})
xrange({start,} stop {, inc}) | Returns a sequence ranging from start to stop in steps of inc; start defaults to 0; inc defaults to 1. Use xrange for large sequences (say more than 20 items) |
range(10) --> [0,1,2,3,4,5,6,7,8,9]
range(9,-1,-1) --> [9,8,7,6,5,4,3,2,1,0] | |
| reduce(func, list {, init}) | Applies func to each pair of items in turn accumulating a result |
reduce(lambda x,y:x+y, [1,2,3,4],5) --> 15
reduce(lambda x,y:x&y, [1,0,1]) --> 0 reduce(None, [], 1) --> 1 | |
|
repr(object)
-- or -- `object` | Convert to a string from which it can be recreated, if possible |
repr(10 * 2) --> "20"
repr('xxx') --> "'xxx'" x = 10; `x` --> "10'" | |
| round(x {, digits}) | Rounds the number |
round(10.009, 2) --> 10.01
round(1.5) --> 2 | |
| str(object) | Converts to human-friendly string |
str(10 * 2) --> "20"
str('xxx') --> 'xxx' | |
| type(object) |
Returns the type (not the same as class) of the object.
To get the class use object.__class__.
Module types has symbolic names for all Jython types
| x = "1"; type(x) is type('') --> 1 | |
| zip(seq, ...) | Zips sequences together; results is only as long as the shortest input sequence | zip([1,2,3],"abc") --> [(1,'a'),(2,'b'),(3,'c')] |
See the Python Library Reference (Resources) for more details.
Appendix F: Jython library summary
Jython supports a large number of Python libraries. By using only these libraries it is possible to write Jython programs that will work in any Python environment. Many of these libraries provide similar function to those provided by the Java APIs. Jython also has access to all Java libraries. This means it can do anything a Java program can do but then it is no longer possible to run the program in a Python environment.
Most libraries that are written in Python and do not depend on operating system specific services are supported without change. Many of these libraries are shipped with Jtyhon. Libraries written in C must be converted; many of the core C libraries have been converted and are shipped with Jython.
Jython also has a few unique libraries of its own. These libraries supplement the extensive API libraries provided by Java itself. For more details on these libraries, read the source files (in <jython_install_dir>/Lib/<lib_name>.py) or see the Python Library Reference (Resources).
Some of the more interesting external libraries supplied with Jython include:
| Library | Comment (often from the library prolog) |
| atexit | Allows a programmer to define multiple exit functions to be executed upon normal program termination |
| base64 | Conversions to/from base64 transport encoding as per RFC-1521 |
| BaseHTTPServer | HTTP server base class (abstract) |
| bdb | Generic Python debugger base class |
| bisect | Some Bisection algorithms |
| calendar | Calendar printing functions (in English) |
| cgi | Support module for CGI (Common Gateway Interface) scripts |
| CGIHTTPServer | CGI-savvy SimpleHTTPServer |
| cmd | A generic class to build line-oriented command interpreters |
| code | Utilities needed to emulate Python's interactive interpreter |
| codecs | Python Codec Registry, API and helpers (abstract) |
| colorsys | Conversion functions between RGB and other color systems |
| ConfigParser | Configuration file parser |
| Cookie | Cookie is a module for the handling of HTTP cookies as a dictionary |
| copy | Generic (shallow and deep) copying operations |
| difflib | Utilities for computing deltas between objects |
| dircache | Read and cache directory listings |
| doctest | A framework for running examples in document strings (sort of like JUnit); I recommend unittest below |
| dumbdbm | A dumb and slow but simple dbm clone |
| fileinput | Class to quickly write a loop over all standard input files |
| fnmatch | Filename matching with shell patterns |
| formatter | Generic output formatting framework (abstract) |
| fpformat | General floating point formatting functions |
| ftplib | An FTP client class and some helper functions |
| getopt | Parser for command line options (UNIX style) |
| glob | Filename globbing (a list of paths matching a pathname pattern) utility |
| gopherlib | Gopher protocol client interface |
| gzip | Functions that read and write gzipped files |
| htmlentitydefs | HTML character entity references |
| httplib | HTTP/1.1 client library |
| imaplib | IMAP4 client |
| imghdr | Recognize selected image file formats based on their first few bytes |
| isql | Provides an interactive environment for database work |
| linecache | Cache lines from files |
| mailcap | Mailcap file handling. See RFC 1524 |
| mimetools | Various tools used by MIME-reading or MIME-writing programs |
| mimetypes | Guess the MIME type of a file |
| MimeWriter | Generic MIME writer |
| mimify | Mimification and unmimification of mail messages |
| multifile | A readline()-style interface to the parts of a multipart message |
| nntplib | An NNTP client class based on RFC 977: Network News Transfer Protocol |
| nturl2path | Convert a NT pathname to a file URL and vice versa |
| pdb | A Python debugger |
| pickle | Create portable serialized representations of Jython (not Java) objects |
| pipes | Conversion pipeline templates |
| poplib | A POP3 client class |
| posixfile | Extended file operations available in POSIX |
| pprint | Support to pretty-print lists, tuples, & dictionaries recursively |
| profile | Class for profiling python code |
| pstats | Class for printing reports on profiled python code |
| pyclbr | Parse a Python file and retrieve classes and methods |
| Queue | A multi-producer, multi-consumer queue |
| quopri | Conversions to/from quoted-printable transport encoding as per RFC-1521 |
| random | Random variable generators |
| re | Regular Expression Engine (clone of sre) |
| repr | Redo the '...' (representation) but with limits on most sizes |
| rfc822 | RFC-822 message manipulation class |
| sched | A generally useful event scheduler class |
| sgmllib | A SAX-like parser for SGML (subset as used by HTML), using the derived class as a static DTD (abstract) |
| shelve | Manage shelves (persistent, dictionary) of pickled objects |
| shutil | Utility functions for copying files and directory trees |
| SimpleHTTPServer | A Simple HTTP Server (text HEAD and GET only) |
| smtplib | SMTP/ESMTP client class that follows RFC-821 (SMTP) and RFC-1869 (ESMTP) |
| sndhdr | Routines to help recognizing select sound files |
| socket | Basic socket support |
| SocketServer | Generic socket server classes |
| sre | Regular Expression Engine |
| stat | Constants/functions for interpreting results of os.stat() and os.lstat() |
| string | Common string manipulations; a (very useful) collection of string operations. The string type also supports most of these functions as methods. |
| StringIO | File-like object that reads from or writes to a string buffer |
| telnetlib | TELNET client class based on RFC-854 |
| tempfile | Temporary files and filenames |
| threading | New threading module, emulating a subset of the Java platform's threading model |
| tokenize | Tokenization help for Python programs |
| traceback | Extract, format and print information about Python stack traces |
| unittest | Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework |
| urllib | Open an arbitrary URL |
| urlparse | Parse (absolute and relative) URLs |
| user | Hook to allow user-specified customization code to run at start-up |
| UserDict | A more or less complete user-defined wrapper around dictionary objects |
| UserList | A more or less complete user-defined wrapper around list objects |
| UserString | A user-defined wrapper around string objects |
| whrandom | Wichman-Hill random number generator |
| xmllib | A SA-like parser for XML, using the derived class as static DTD (abstract) |
| zipfile | Read and write ZIP files |
| __future__ | Used to access features from future versions that are available (potentially in less than finished form) today |
Note: I do not claim the above library modules work or are error free on Jython, especially when you are not running on a UNIX system. Try them interactively before you decide to code to them.
Appendix G: Jython types summary
Jython supports many object types. The module types defines symbols for these types. The function type gets the type of any object. The type value can be tested (see Dynamic type testing). The table below summarizes the most often used types.
| Type symbol | Jython runtime type | Comment(s) |
| ArrayType | PyArray | Any array object |
| BuiltinFunctionType | PyReflectedFunction | Any built-in function object |
| BuiltinMethodType | PyMethod | Any built-in method object |
| ClassType | PyClass | Any Jython class object |
| ComplexType | PyComplex | Any complex object |
|
DictType
-- or -- DictionaryType | PyDictionary | Any dictionary object |
| FileType | PyFile | Any file object |
| FloatType | PyFloat | Any float object |
| FunctionType | PyFunction | Any function object |
| InstanceType | PyInstance | Any class instance object |
| -- none -- | PyJavaInstance | Any Java class instance object |
| IntType | PyInteger | Any integer object |
| LambdaType | PyFunction | Any lambda function expression object |
| ListType | PyList | Any list object |
| LongType | PyLong | Any long object |
| MethodType | PyMethod | Any non-built-in method object |
| ModuleType | PyModule | Any module object |
| NoneType | PyNone | Any None (only one) object |
| StringType | PyString | Any ASCII string object |
| TracebackType | PyTraceback | Any exception traceback object |
| TupleType | PyTuple | Any tuple object |
| TypeType | PyJavaClass | Any type object |
| UnboundMethodType | PyMethod | Any method (without a bound instancee) object |
| UnicodeType | PyString | Any Unicode string object |
| XRangeType | PyXRange | Any extended range object |
Note: several types map to the same Java runtime type.
For more information on types see the Python Library Reference (Resources).
The format operator (see Formatting strings and values supports the following format characters:
| Character(s) | Result Format | Comment(s) |
| %s, %r | String |
%s does str(x), %r does repr(x)
|
| %i, %d | Integer Decimal | Basically the same format |
| %o, %u, %x, %X | Unsigned Value | In octal, unsigned decimal, hexadecimal |
| %f, %F | Floating Decimal | Shows fraction after decimal point |
| %e, %E, %g, %G | Exponential | %g is %f unless the value is small; else %e |
| %c | Character | Must be a single character or integer |
| %% | Character | The % character |
Note: more details on the structure and options of the format item can be found in the Python Library Reference (Resources). Use of case in format characters (for example, X vs x causes the symbol to show in matching case.

