- Details
- Category: Dive Into Python
- Hits: 12162
{article Python Content}{title} {text} {/article}
The below example are from the book
Dive Into Python
Dive Into Python is a free Python book for experienced programmers.
Run in Python Shell
- Details
- Category: Dive Into Python
- Hits: 1884
{article Dive into Python}{title} {text}{/article}
Defining Lists | Negative List Indices | Slicing a List | Slicing Shorthand |
Adding Elements to Lists | The Difference between extend and append | Searching Lists | Removing Elements from a Lists |
List Operators |
In Python, the closest object to an array is a list,
Lists in Python are created by comma-separated values, between square brackets.
List items do not need to have all the same data type. Unlike strings which are immutable, it is possible to change individual elements of
a list (lists are mutable):
immutable object is an object whose state cannot be modified after it is created
mutable object, which can be modified after it is created.
- li = ["a", "b", "mpilgrim", "z", "example"]
- li[0]
- li[4]
- First, you define a list of five elements.
- A list can be used like a zero−based array. The first element of any non−empty list is always li[0].
- The last element of this five−element list is li[4], because lists are always zero−based.
{source}
<!-- You can place html anywhere within the source tags -->
<!-- <link type="text/css" rel="Stylesheet" href="/syntaxhighlighter_3.0.83/styles/shThemeDefault.css"/> -->
<pre class="brush:py;">
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> li = ["a", "b", "mpilgrim", "z", "example"] #First, you define a list of five elements.
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[0] # A list can be used like a zero−based array. The first element of any non−empty list is always li[0].
'a'
>>> li[4] # The last element of this five−element list is li[4], because lists are always zero−based.
'example'
>>>
</pre>
<script language="javascript" type="text/javascript">
// You can place JavaScript like this
</script>
<?php
// You can place PHP like this
?>
{/source}
- li[-1]
- li[-3]
- A negative index accesses elements from the end of the list counting backwards. The last element of
any non−empty list is always li[−1]. - If the negative index is confusing to you, think of it this way: li[−n] == li[len(li) − n]. So
in this list, li[−3] == li[5 − 3] == li[2].
{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">
>>> li = ["a", "b", "mpilgrim", "z", "example"] # First, you define a list of five elements.
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1] # A negative index accesses elements from the end of the list counting backwards. The last element of any non−empty list is always li[−1].
'example'
>>> li[-3] # If the negative index is confusing to you, think of it this way: li[−n] == li[len(li) − n]. So in this list, li[−3] == li[5 − 3] == li[2].
'mpilgrim'
>>>
</pre>
<script language="javascript" type="text/javascript">
// You can place JavaScript like this
</script>
<?php
// You can place PHP like this
?>
{/source}
li
- li[1:3]
- li[1:-1]
- li[0:3]
- You can get a subset of a list, called a "slice", by specifying two indices. The return value is a new list
containing all the elements of the list, in order, starting with the first slice index (in this case li[1]), up to but
not including the second slice index (in this case li[3]).
Slicing works if one or both of the slice indices is negative. If it helps, you can think of it this way: reading the
list from left to right, the first slice index specifies the first element you want, and the second slice index
specifies the first element you don't want. The return value is everything in between.
Lists are zero−based, so li[0:3] returns the first three elements of the list, starting at li[0], up to but not
including li[3].
>>> li = ["a", "b", "mpilgrim", "z", "example"]
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
1.>>> li[:3]
['a', 'b', 'mpilgrim']
2. 3.>>> li[3:]
['z', 'example']
4. >>> li[:]
['a', 'b', 'mpilgrim', 'z', 'example']
>>>
- If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3] is the same as li[0:3] from
Example 3.8, Slicing a List.
Similarly, if the right slice index is the length of the list, you can leave it out. So li[3:] is the same as
li[3:5], because this list has five elements.- Note the symmetry here. In this five−element list, li[:3] returns the first 3 elements, and li[3:] returns
the last two elements. In fact, li[:n] will always return the first n elements, and li[n:] will return the rest,
regardless of the length of the list.
If both slice indices are left out, all elements of the list are included. But this is not the same as the original li
list; it is a new list that happens to have all the same elements. li[:] is shorthand for making a complete copy
of a list.
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
1. >>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
2. >>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
3. >>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
- append adds a single element to the end of the list.
insert inserts a single element into a list. The numeric argument is the index of the first element that gets
bumped out of position. Note that list elements do not need to be unique; there are now two separate elements with the value 'new', li[2] and li[6].
extend concatenates lists. Note that you do not call extend with multiple arguments; you call it with one
argument, a list. In this case, that list has two elements.
The Difference between extend and append
>>> li = ['a', 'b', 'c']
>>> li
['a', 'b', 'c']
1.>>> li.extend(['d', 'e', 'f'])
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
2.>>> len(li)
6
>>> li[-1]
'f'
>>> li = ['a', 'b', 'c']
3.>>> li.append(['d', 'e', 'f'])
>>> li
['a', 'b', 'c', ['d', 'e', 'f']]
4.>>> len(li)
4
>>> li[-1]
['d', 'e', 'f']
- Lists have two methods, extend and append, that look like they do the same thing, but are in fact
completely different. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list. - Here you started with a list of three elements ('a', 'b', and 'c'), and you extended the list with a list of another three elements ('d', 'e', and 'f'), so you now have a list of six elements
- On the other hand, append takes one argument, which can be any data type, and simply adds it to the
end of the list. Here, you're calling the append method with a single argument, which is a list of three elements. - Now the original list, which started as a list of three elements, contains four elements. Why four? Because the last element that you just appended is itself a list. Lists can contain any type of data, including other lists. That may be what you want, or maybe not. Don't use append if you mean extend.
li = ["a", "b", "new", "mpilgrim", "z", "example", "new", "two", "elements"]
- li.index("example")
- li.index("new")
- li.index("c")
- "c" in li
- index finds the first occurrence of a value in the list and returns the index.
- index finds the first occurrence of a value in the list. In this case, 'new' occurs twice in the list, in li[2] and li[6], but index will return only the first index, 2.
- If the value is not found in the list, Python raises an exception. This is notably different from most languages, which will return some invalid index. While this may seem annoying, it is a good thing, because it means your program will crash at the source of the problem, rather than later on when you try to use the invalid index.
- To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.
- li.remove("z")
- li.remove("new")
- li.remove("c")
- li.pop()
- remove removes the first occurrence of a value(z) from a list.
- remove removes only the first occurrence of a value. In this case, 'new' appeared twice in the list, but li.remove("new") removed only the first occurrence.
- If the value is not found in the list, Python raises an exception. This mirrors the behavior of the index method.
- pop is an interesting beast. It does two things: it removes the last element of the list, and it returns the value that it removed. Note that this is different from li[−1], which returns a value but does not change the list, and different from li.remove(value), which changes the list but does not return a value.
li = ['a', 'b', 'mpilgrim']
- li = li + ['example', 'new']
- li += ['two']
- li = [1, 2] * 3
- Lists can also be concatenated with the + operator. list = list + otherlist has the
same result as list.extend(otherlist). But the + operator returns a new (concatenated)
list as a value, whereas extend only alters an existing list. This means that extend is faster,
especially for large lists.
Python supports the += operator. li += ['two'] is equivalent to li.extend(['two']).
The += operator works for lists, strings, and integers, and it can be overloaded to work for
user−defined classes as well. (More on classes in Chapter 5.).
The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1,
2] + [1, 2] + [1, 2], which concatenates the three lists into one.
- Details
- Category: Dive Into Python
- Hits: 1744
{article Dive into Python}{title} {text}{/article}
A tuple is an immutable list. A tuple can not be changed in any way once it is created, tuples are immutable and tuples use ( ) parentheses and lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also.
Tuples may be created directly or converted from lists. Generally, tuples are enclosed in parentheses.
These are the same as for lists except that we may not assign to indices or slices, and there is no "append" operator.
Defining a tuple
- tuple = ("a", "b", "mpilgrim", "z", "example")
- tuple[0]
- tuple[-1]
- tuple[1:3]
- A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.
The elements of a tuple have a defined order, just like a list. Tuples indices are zero−based, just like a list, so the first element of a non−empty tuple is always t[0].
Negative indices count from the end of the tuple, just as with a list.
Slicing works too, just like a list. Note that when you slice a list, you get a new list; when you slice a tuple, you get a new tuple.
tuple = ("a", "b", "mpilgrim", "z", "example")
tuple
('a', 'b', 'mpilgrim', 'z', 'example')
tuple[0]
'a'
tuple[-1]
'example'
tuple[1:3]
('b', 'mpilgrim')
Tuples Have No Methods
These are the same as for lists except that we may not assign to indices or slices, and there is no "append" operator.
t = ("a", "b", "mpilgrim", "z", "example")
- t.append("new")
t.remove("z")
t.index("example")
"z" in t
- You can't add elements to a tuple. Tuples have no append or extend method.
You can't remove elements from a tuple. Tuples have no remove or pop method.
You can't find elements in a tuple. Tuples have no index method.
You can, however, use in to see if an element exists in the tuple.
Tuples can be converted into lists, and vice−versa.
The built−in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list.
In effect, tuple freezes a list, and list thaws a tuple.
- Details
- Category: Dive Into Python
- Hits: 1653
{article Dive into Python}{title} {text}{/article}
Python has local and global variables like most other languages, but it has no explicit variable declarations.
Variables spring into existence by being assigned a value, and they are automatically destroyed when they go out of scope.
Python will not allow you to reference a variable that has never been assigned a value; trying to do so will raise an exception.
You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.
That the variable assignment is one command split over several lines, with a backslash ("\") serving as a
line−continuation marker.
Strictly speaking, expressions in parentheses, straight brackets, or curly braces (like defining a dictionary) can be split into multiple lines with or without the line continuation character ("\"). I like to include the backslash even when it's not required because I think it makes the code easier to read, but that's a matter of style.
Referencing an Unbound Variable
Assigning Multiple Values at Once
v = ('a', 'b', 'e')
- (x, y, z) = v
- v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other
assigns each of the values of v to each of the variables, in order.
This has all sorts of uses. I often want to assign names to a range of values. In C, you would use enum and manually list each constant and its associated value, which seems especially tedious when the values are consecutive. In Python, you can use the built−in range function with multi−variable assignment to quickly assign consecutive values.
Assigning Consecutive Values
- range(7)
- (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
- >>> MONDAY
- 0
- The built−in range function returns a list of integers. In its simplest form, it takes an upper limit and returns a zero−based list counting up to but not including the upper limit. (If you like, you can pass other parameters to specify a base other than 0 and a step other than 1. You can print range.__doc__ for details.)
- MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are the variables you're defining. (This example came from the calendar module, a fun little module that prints calendars, like the UNIX program cal. The calendar module defines integer constants for days of the week.)
- Now each variable has its value: MONDAY is 0, TUESDAY is 1, and so forth.
Autocompletion
A handy short cut. Idle remembers all the variables you have defined at any moment. This is
handy when editing. Without pressing Enter, type into the Shell just
f
Then hold down the Alt key and press the / key. This key combination is abbreviated Alt-/. (On a Mac, that may give you a funny character: In that case you need to hold down both the control key and the alt/option key when pressing the ‘/’. This may hold in other places the Alt key is called for in Windows.)
You should see f autocompleted to be
first
- Details
- Category: Dive Into Python
- Hits: 1059
{article Dive into Python}{title} {text}{/article}
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.
- print ("Today's stock price: %f" % 50.4625)
- print ("Today's stock price: %.2f" % 50.4625)
- print ("Today's stock price: %+.2f" % 1.5)
- The %f string formatting option treats the value as a decimal, and prints it to six decimal places.
- The ".2" modifier of the %f option truncates the value to two decimal places.
- You can even combine modifiers. Adding the + modifier displays a plus or minus sign before the value. Note that the ".2" modifier is still in place, and is padding the value to exactly two decimal places.
Conversion | Meaning |
---|---|
%d | Signed integer decimal. |
%i | Signed integer decimal. |
%o | Signed octal value. |
%u | Obsolete type – it is identical to 'd'. |
%x | Signed hexadecimal (lowercase). |
%X | Signed hexadecimal (uppercase). |
%e | Floating point exponential format (lowercase). |
%E | Floating point exponential format (uppercase). |
%f | Floating point decimal format. |
%F | Floating point decimal format. |
%g | Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
%G | Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
%c | Single character (accepts integer or single character string). |
%r | String (converts any Python object using repr()). |
%s | String (converts any Python object using str()). |
% | No argument is converted, results in a '%' character in the result. |
How to print a string
>>> string = "# How to print a string."
>>> print (string)
# How to print a string.
>>> print string
SyntaxError: invalid syntax
k = "uid"
v = "sa"
"%s=%s" % (k, v)
Concatenating
>>> uid = "sa"
>>> pwd = "secret"
1: >>> print pwd + " is not a good password for " + uid
SyntaxError: invalid syntax
>>> print (pwd + " is not a good password for " + uid)
secret is not a good password for sa
>>> print "%s is not a good password for %s" % (pwd, uid)
SyntaxError: invalid syntax
>>> print ("%s is not a good password for %s") % (pwd, uid)
%s is not a good password for %s
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print ("%s is not a good password for %s") % (pwd, uid)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
2: >>> print ("%s is not a good password for %s" % (pwd, uid))
secret is not a good password for sa
>>> userCount = 6
3: 4: >>> print ("Users connected: %d" % (userCount, ))
Users connected: 6
5: >>> print ("Users connected: " + userCount)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
print ("Users connected: " + userCount)
TypeError: Can't convert 'int' object to str implicitly
>>>
- + is the string concatenation operator.
In this trivial case, string formatting accomplishes the same result as concatentation.
(userCount, ) is a tuple with one element. Yes, the syntax is a little strange, but there's a good reason for
it: it's unambiguously a tuple. In fact, you can always include a comma after the last element when defining a
list, tuple, or dictionary, but the comma is required when defining a tuple with one element. If the comma
weren't required, Python wouldn't know whether (userCount) was a tuple with one element or just the value
of userCount.
String formatting works with integers by specifying %d instead of %s.
Trying to concatenate a string with a non−string raises an exception. Unlike string formatting, string
concatenation works only when everything is already a string.
As with printf in C, string formatting in Python is like a Swiss Army knife. There are options galore, and modifier
strings to specially format many different types of values.
Numbers
>>> print("{:.2f}".format(3.1415926)) 2 decimal places
3.14
>>> print("{:+.2f}".format(+3.1415926)) 2 decimal places with sign
+3.14
>>> print("{:+.2f}".format(-1)) 2 decimal places with sign
-1.00
>>> print("{:.0f}".format(2.71828)) No decimal places
3
>>> print("{:0>2d}".format(5)) Pad number with zeros (left padding, width 2)
05
>>> print("{:x<4d}".format(5)) Pad number with x's (right padding, width 4)
5xxx
>>> print("{:x<4d}".format(10)) Pad number with x's (right padding, width 4)
10xx
>>> print("{:,}".format(1000000)) Number format with comma separator
1,000,000
>>> print("{:.2%}".format(0.25)) Format percentage
25.00%
>>> print("{:.2e}".format(1000000000)) Exponent notation
1.00e+09
>>> print("{:10d}".format(13)) Right aligned (default, width 10)
13
>>> print("{:<10d}".format(13)) Left aligned (width 10)
13
>>> print("{:^10d}".format(13)) Center aligned (width 10)
13
Type |
Meaning |
'e' |
Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6. |
'E' |
Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character. |
'f' |
Fixed point. Displays the number as a fixed-point number. The default precision is 6. |
'F' |
Fixed point. Same as 'f', but converts nan to NAN and inf to INF. |
'g' |
General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it. Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision. A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6. |
'G' |
General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too. |
'n' |
Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters. |
'%' |
Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign. |
None |
Similar to 'g', except with at least one digit past the decimal point and a default precision of 12. This is intended to match str(), except you can add the other format modifiers. |
Option | Meaning |
---|---|
'<' | Forces the field to be left-aligned within the available space (this is the default for most objects). |
'>' | Forces the field to be right-aligned within the available space (this is the default for numbers). |
'=' | Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. |
'^' | Forces the field to be centered within the available space. |
- Details
- Category: Dive Into Python
- Hits: 1726
{article Dive into Python}{title} {text}{/article}
One of the most powerful features of Python is the list comprehension, which provides a compact way of mapping a list into another list by applying a function to each of the elements of the list.
Introducing List Comprehensions
- li = [1, 9, 8, 4]
- [elem*2 for elem in li]
- li = [elem*2 for elem in li]
- To make sense of this, look at it from right to left. li is the list you're mapping. Python loops through li one element at a time, temporarily assigning the value of each element to the variable elem. Python then applies the function elem*2 and appends that result to the returned list.
- Note that list comprehensions do not change the original list.
- It is safe to assign the result of a list comprehension to the variable that you're mapping. Python constructs the new list in memory, and when the list comprehension is complete, it assigns the result to the variable
The keys, values, and items Functions
Description: keys() Method
The method keys() returns a list of all the available keys in the dictionary.
Syntax
Following is the syntax for keys() method:
dict.keys()
Description: values() Method
The method values() returns a list of all the values available in a given dictionary.
Syntax
Following is the syntax for values() method:
dict.values()
Description items() Method
The method items() returns a list of dict's (key, value) tuple pairs
Syntax
Following is the syntax for items() method:
dict.items()
params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
- params.keys()
- params.values()
- params.items()
- The keys method of a dictionary returns a list of all the keys. The list is not in the order inwhich the dictionary was defined (remember that elements in a dictionary are unordered),but it is a list.
- The values method returns a list of all the values. The list is in the same order as the listreturned by keys, so params.values()[n] == params[params.keys()[n]] for all values of n.
- The items method returns a list of tuples of the form (key, value). The list containsall the data in the dictionary.
List Comprehensions in buildConnectionString, Step by Step
params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
params.items()
- [k for k, v in params.items()]
- [v for k, v in params.items()]
- ["%s=%s" % (k, v) for k, v in params.items()]
- Note that you're using two variables to iterate through the params.items() list. This is another use of multi−variable assignment. The first element of params.items() is ('server', 'mpilgrim'), so in the first iteration of the list comprehension, k will get 'server' and v will get 'mpilgrim'. In this case, you're ignoring the value of v and only including the value of k in the returned list, so this list comprehensionends up being equivalent to params.keys().
- Here you're doing the same thing, but ignoring the value of k, so this list comprehension ends up being equivalent to params.values().
- Combining the previous two examples with some simple string formatting, you get a list of strings that include both the key and value of each element of the dictionary. This looks suspiciously like the output of the program. All that remains is to join the elements in this list into a single string.
A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values.
Python dictionaries are also known as associative arrays or hash tables.
The general syntax of a dictionary is as follows:
dict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
dict.keys()
dict.values()
dict.items()
Mapping Types — dict
- d[key] = value
-
Set d[key] to value.
- del d[key]
-
Remove d[key] from d. Raises a KeyError if key is not in the map.
- key in d
-
Return True if d has a key key, else False.
- key not in d
-
Equivalent to not key in d.
- iter(d)
-
Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).
- clear()
-
Remove all items from the dictionary.
- copy()
-
Return a shallow copy of the dictionary.
- classmethod fromkeys(seq[, value])
-
Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.
- get(key[, default])
-
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
- items()
-
Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.
- keys()
-
Return a new view of the dictionary’s keys. See the documentation of view objects.
- pop(key[, default])
-
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
- popitem()
-
Remove and return an arbitrary (key, value) pair from the dictionary.
popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.
- setdefault(key[, default])
-
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
- update([other])
-
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
- values()
-
Return a new view of the dictionary’s values. See the documentation of view objects.
- Details
- Category: Dive Into Python
- Hits: 1552
{article Dive into Python}{title} {text}{/article}
You have a list of key−value pairs in the form key=value, and you want to join them into a single string. To join any list of strings into a single string, use the join method of a string object.
The join method joins the elements of the list into a single string, with each element separated by a semi−colon. The delimiter doesn't need to be a semi−colon; it doesn't even need to be a single character. It can be any string.
join works only on lists of strings; it does not do any type coercion. Joining a list that has one or more non−string elements will raise an exception.
Example
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s = "Joining Lists and Splitting String"
>>> s.split()
['Joining', 'Lists', 'and', 'Splitting', 'String']
>>> 'Joining Lists and Splitting String'.split()
['Joining', 'Lists', 'and', 'Splitting', 'String']
>>> s.split ('i')
['Jo', 'n', 'ng L', 'sts and Spl', 'tt', 'ng Str', 'ng']
>>> string = s.split()
>>> string
['Joining', 'Lists', 'and', 'Splitting', 'String']
>>> for s in string: print(s)
Joining
Lists
and
Splitting
String
>>> new = ':'.join(string)
>>> new
'Joining:Lists:and:Splitting:String'
>>> ', '.join(string)
'Joining, Lists, and, Splitting, String'
>>>
- Details
- Category: Dive Into Python
- Hits: 1544
{article Dive into Python}{title} {text} {readmore}{/article}
introspection
the process of examining your own thoughts or feelings; the act of looking within oneself.
In computer programming, introspection refers to the ability to examine something to determine what it is, what it knows, and what it is capable of doing.
Run Mofule apihelper.py
Sample Usage of apihelper.py
"""Cheap and simple API helper
This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""
__author__ = "Mark Pilgrim (
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"
# While this is a good example script to teach about introspection,
# in real life it has been superceded by PyDoc, which is part of the
# standard library in Python 2.1 and later.
#
# Your IDE may already import the "help" function from pydoc
# automatically on startup; if not, do this:
#
# >>> from pydoc import help
#
# The help function in this module takes the object itself to get
# help on, but PyDoc can also take a string, like this:
#
# >>> help("string") # gets help on the string module
# >>> help("apihelper.help") # gets help on the function below
# >>> help() # enters an interactive help mode
#
# PyDoc can also act as an HTTP server to dynamically produce
# HTML-formatted documentation of any module in your path.
# That's wicked cool. Read more about PyDoc here:
# http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print ("\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList]))
if __name__ == "__main__":
print (help.__doc__)
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ==================================================== RESTART ====================================================
>>>
Define the builtin 'help'.
This is a wrapper around pydoc.help (with a twist).
>>> from apihelper import info
>>> li = []
>>> info(li)
__add__ Return self+value.
__class__ list() -> new empty list list(iterable) -> new list initialized from iterable's items
__contains__ Return key in self.
__delattr__ Implement delattr(self, name).
__delitem__ Delete self[key].
__dir__ __dir__() -> list default dir() implementation
__eq__ Return self==value.
__format__ default object formatter
__ge__ __ge__=($self, value, /) -- Return self>=value.
__getattribute__ Return getattr(self, name).
__getitem__ x.__getitem__(y) <==> x[y]
__gt__ Return self>value.
__iadd__ Implement self+=value.
__imul__ Implement self*=value.
__init__ Initialize self. See help(type(self)) for accurate signature.
__iter__ Implement iter(self).
__le__ Return self<=value.
__len__ Return len(self).
__lt__ Return self<value.
__mul__ Return self*value.n
__ne__ Return self!=value.
__new__ Create and return a new object. See help(type) for accurate signature.
__reduce__ helper for pickle
__reduce_ex__ helper for pickle
__repr__ Return repr(self).
__reversed__ L.__reversed__() -- return a reverse iterator over the list
__rmul__ Return self*value.
__setattr__ Implement setattr(self, name, value).
__setitem__ Set self[key] to value.
__sizeof__ L.__sizeof__() -- size of L in memory, in bytes
__str__ Return str(self).
__subclasshook__ Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
append L.append(object) -> None -- append object to end
clear L.clear() -> None -- remove all items from L
copy L.copy() -> list -- a shallow copy of L
count L.count(value) -> integer -- return number of occurrences of value
extend L.extend(iterable) -> None -- extend list by appending elements from the iterable
index L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.
insert L.insert(index, object) -- insert object before index
pop L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.
remove L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present.
reverse L.reverse() -- reverse *IN PLACE*
sort L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
Advanced Usage of apihelper.py
import odbchelper
info(odbchelper)
info(odbchelper, 30)
info(odbchelper, 30, 0)
introspection techniques
def interrogate(item):
"""Print useful information about item."""
if hasattr(item, '__name__'):
print ("NAME: ", item.__name__)
if hasattr(item, '__class__'):
print ("CLASS: ", item.__class__.__name__)
print ("ID: ", id(item))
print ("TYPE: ", type(item))
print ("VALUE: ", repr(item))
print ("CALLABLE:"),
if callable(item):
print ("Yes")
else:
print ("No")
if hasattr(item, '__doc__'):
doc = getattr(item, '__doc__')
doc = doc.strip() # Remove leading/trailing whitespace.
firstline = doc.split('\n')[0]
print ("DOC: ", firstline)
interrogate.py
>>> interrogate('a string') # String object
CLASS: str
ID: 59981488
TYPE: <class 'str'>
VALUE: 'a string'
CALLABLE:
No
DOC: str(object='') -> str
>>> interrogate(42) # Integer object
CLASS: int
ID: 1602520544
TYPE: <class 'int'>
VALUE: 42
CALLABLE:
No
DOC: int(x=0) -> integer
>>> interrogate(interrogate) # User-defined function object
NAME: interrogate
CLASS: function
ID: 59993080
TYPE: <class 'function'>
VALUE: <function interrogate at 0x0000000003936BF8>
CALLABLE:
Yes
DOC: Print useful information about item.
>>>
- Details
- Category: Dive Into Python
- Hits: 1533
{article Dive into Python}{title} {text}{/article}
Run Module
"""Cheap and simple API helper
This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""
__author__ = "Mark Pilgrim (
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"
# While this is a good example script to teach about introspection,
# in real life it has been superceded by PyDoc, which is part of the
# standard library in Python 2.1 and later.
#
# Your IDE may already import the "help" function from pydoc
# automatically on startup; if not, do this:
#
# >>> from pydoc import help
#
# The help function in this module takes the object itself to get
# help on, but PyDoc can also take a string, like this:
#
# >>> help("string") # gets help on the string module
# >>> help("apihelper.help") # gets help on the function below
# >>> help() # enters an interactive help mode
#
# PyDoc can also act as an HTTP server to dynamically produce
# HTML-formatted documentation of any module in your path.
# That's wicked cool. Read more about PyDoc here:
# http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print ("\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList]))
if __name__ == "__main__":
print (help.__doc__)
info(odbchelper)
info(odbchelper, 12)
info(odbchelper, collapse=0)
info(spacing=15, object=odbchelper)
- Details
- Category: Dive Into Python
- Hits: 1729
{article Dive into Python}{title} {text}{/article}
Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.
Built-in Functions |
||||
|
||||
|
- Details
- Category: Dive Into Python
- Hits: 1656
{article Dive into Python}{title} {text}{/article}
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.
The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.
- >>> type(1)
<class 'int'>
>>> li = [] - >>> type(li)
<class 'list'>
>>> import odbchelper - >>> type(odbchelper)
<class 'module'> - >>> import types
>>> type(odbchelper) == types.ModuleType
True
>>>
- type takes anything −− and I mean anything −− and returns its datatype. Integers, strings, lists,dictionaries, tuples, functions, classes, modules, even types are acceptable.
- type can take a variable and return its datatype.
- type also works on modules.
- You can use the constants in the types module to compare types of objects. This is what the info
function does, as you'll see shortly