"hello world"
'hello world'
'hello again'
'hello again'
"""A string
that spans
multiple
lines"""
# Note how python identifies `\n` as the linebreak character
'A string\nthat spans\nmultiple\nlines'
hw = "hello world"
print hw
hello world
help(str)
Help on class str in module __builtin__: class str(basestring) | str(object) -> string | | Return a nice string representation of the object. | If the argument is a string, the return value is the same object. | | Method resolution order: | str | basestring | object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __eq__(...) | x.__eq__(y) <==> x==y | | __format__(...) | S.__format__(format_spec) -> string | | Return a formatted version of S as described by format_spec. | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getnewargs__(...) | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __mod__(...) | x.__mod__(y) <==> x%y | | __mul__(...) | x.__mul__(n) <==> x*n | | __ne__(...) | x.__ne__(y) <==> x!=y | | __repr__(...) | x.__repr__() <==> repr(x) | | __rmod__(...) | x.__rmod__(y) <==> y%x | | __rmul__(...) | x.__rmul__(n) <==> n*x | | __sizeof__(...) | S.__sizeof__() -> size of S in memory, in bytes | | __str__(...) | x.__str__() <==> str(x) | | capitalize(...) | S.capitalize() -> string | | Return a copy of the string S with only its first character | capitalized. | | center(...) | S.center(width[, fillchar]) -> string | | Return S centered in a string of length width. Padding is | done using the specified fill character (default is a space) | | count(...) | S.count(sub[, start[, end]]) -> int | | Return the number of non-overlapping occurrences of substring sub in | string S[start:end]. Optional arguments start and end are interpreted | as in slice notation. | | decode(...) | S.decode([encoding[,errors]]) -> object | | Decodes S using the codec registered for encoding. encoding defaults | to the default encoding. errors may be given to set a different error | handling scheme. Default is 'strict' meaning that encoding errors raise | a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' | as well as any other name registered with codecs.register_error that is | able to handle UnicodeDecodeErrors. | | encode(...) | S.encode([encoding[,errors]]) -> object | | Encodes S using the codec registered for encoding. encoding defaults | to the default encoding. errors may be given to set a different error | handling scheme. Default is 'strict' meaning that encoding errors raise | a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and | 'xmlcharrefreplace' as well as any other name registered with | codecs.register_error that is able to handle UnicodeEncodeErrors. | | endswith(...) | S.endswith(suffix[, start[, end]]) -> bool | | Return True if S ends with the specified suffix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | suffix can also be a tuple of strings to try. | | expandtabs(...) | S.expandtabs([tabsize]) -> string | | Return a copy of S where all tab characters are expanded using spaces. | If tabsize is not given, a tab size of 8 characters is assumed. | | find(...) | S.find(sub [,start [,end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | format(...) | S.format(*args, **kwargs) -> string | | Return a formatted version of S, using substitutions from args and kwargs. | The substitutions are identified by braces ('{' and '}'). | | index(...) | S.index(sub [,start [,end]]) -> int | | Like S.find() but raise ValueError when the substring is not found. | | isalnum(...) | S.isalnum() -> bool | | Return True if all characters in S are alphanumeric | and there is at least one character in S, False otherwise. | | isalpha(...) | S.isalpha() -> bool | | Return True if all characters in S are alphabetic | and there is at least one character in S, False otherwise. | | isdigit(...) | S.isdigit() -> bool | | Return True if all characters in S are digits | and there is at least one character in S, False otherwise. | | islower(...) | S.islower() -> bool | | Return True if all cased characters in S are lowercase and there is | at least one cased character in S, False otherwise. | | isspace(...) | S.isspace() -> bool | | Return True if all characters in S are whitespace | and there is at least one character in S, False otherwise. | | istitle(...) | S.istitle() -> bool | | Return True if S is a titlecased string and there is at least one | character in S, i.e. uppercase characters may only follow uncased | characters and lowercase characters only cased ones. Return False | otherwise. | | isupper(...) | S.isupper() -> bool | | Return True if all cased characters in S are uppercase and there is | at least one cased character in S, False otherwise. | | join(...) | S.join(iterable) -> string | | Return a string which is the concatenation of the strings in the | iterable. The separator between elements is S. | | ljust(...) | S.ljust(width[, fillchar]) -> string | | Return S left-justified in a string of length width. Padding is | done using the specified fill character (default is a space). | | lower(...) | S.lower() -> string | | Return a copy of the string S converted to lowercase. | | lstrip(...) | S.lstrip([chars]) -> string or unicode | | Return a copy of the string S with leading whitespace removed. | If chars is given and not None, remove characters in chars instead. | If chars is unicode, S will be converted to unicode before stripping | | partition(...) | S.partition(sep) -> (head, sep, tail) | | Search for the separator sep in S, and return the part before it, | the separator itself, and the part after it. If the separator is not | found, return S and two empty strings. | | replace(...) | S.replace(old, new[, count]) -> string | | Return a copy of string S with all occurrences of substring | old replaced by new. If the optional argument count is | given, only the first count occurrences are replaced. | | rfind(...) | S.rfind(sub [,start [,end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | rindex(...) | S.rindex(sub [,start [,end]]) -> int | | Like S.rfind() but raise ValueError when the substring is not found. | | rjust(...) | S.rjust(width[, fillchar]) -> string | | Return S right-justified in a string of length width. Padding is | done using the specified fill character (default is a space) | | rpartition(...) | S.rpartition(sep) -> (head, sep, tail) | | Search for the separator sep in S, starting at the end of S, and return | the part before it, the separator itself, and the part after it. If the | separator is not found, return two empty strings and S. | | rsplit(...) | S.rsplit([sep [,maxsplit]]) -> list of strings | | Return a list of the words in the string S, using sep as the | delimiter string, starting at the end of the string and working | to the front. If maxsplit is given, at most maxsplit splits are | done. If sep is not specified or is None, any whitespace string | is a separator. | | rstrip(...) | S.rstrip([chars]) -> string or unicode | | Return a copy of the string S with trailing whitespace removed. | If chars is given and not None, remove characters in chars instead. | If chars is unicode, S will be converted to unicode before stripping | | split(...) | S.split([sep [,maxsplit]]) -> list of strings | | Return a list of the words in the string S, using sep as the | delimiter string. If maxsplit is given, at most maxsplit | splits are done. If sep is not specified or is None, any | whitespace string is a separator and empty strings are removed | from the result. | | splitlines(...) | S.splitlines([keepends]) -> list of strings | | Return a list of the lines in S, breaking at line boundaries. | Line breaks are not included in the resulting list unless keepends | is given and true. | | startswith(...) | S.startswith(prefix[, start[, end]]) -> bool | | Return True if S starts with the specified prefix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | prefix can also be a tuple of strings to try. | | strip(...) | S.strip([chars]) -> string or unicode | | Return a copy of the string S with leading and trailing | whitespace removed. | If chars is given and not None, remove characters in chars instead. | If chars is unicode, S will be converted to unicode before stripping | | swapcase(...) | S.swapcase() -> string | | Return a copy of the string S with uppercase characters | converted to lowercase and vice versa. | | title(...) | S.title() -> string | | Return a titlecased version of S, i.e. words start with uppercase | characters, all remaining cased characters have lowercase. | | translate(...) | S.translate(table [,deletechars]) -> string | | Return a copy of the string S, where all characters occurring | in the optional argument deletechars are removed, and the | remaining characters have been mapped through the given | translation table, which must be a string of length 256 or None. | If the table argument is None, no translation is applied and | the operation simply removes the characters in deletechars. | | upper(...) | S.upper() -> string | | Return a copy of the string S converted to uppercase. | | zfill(...) | S.zfill(width) -> string | | Pad a numeric string S with zeros on the left, to fill a field | of the specified width. The string S is never truncated. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T
new_string = "hello" + "world" # Note no spaces within the "s!
print new_string
helloworld
new_string = "hello " + "world" # Note the space
print new_string
hello world
print "This is the first %s %s wrote" % ( "code", "Jose" )
This is the first code Jose wrote
what_wrote = "code"
who_wrote = "Jose"
what_year = 2012
print "This is the first %s %s wrote in %d" % ( what_wrote, who_wrote, what_year )
This is the first code Jose wrote in 2012
Strings are objects and have methods associated with them. Methods are just a number of ways to do something with objects. For example, for a string, you might want to split it into substrings, find where one substring starts, or replace substrings with other substrings... Have a look at string documentation
hw = "hello world"
hw.count ( "l" ) # Count the number of times "l" apears in hw
3
hw.find ( "l" ) # Find the first location of "l" in hw. Note that python starts counting at 0, not 1!
2
hw.find ( "lo" ) # Ditto
3
hw.isdigit () # Is this string a digit?
False
hw.replace ( "world", "everyone" ) # Replace one substring with another
'hello everyone'
hw.split () # Split the string into words
['hello', 'world']
line = raw_input ( "Enter something: " )
line = line.strip()
while True:
if line == "" or line == "q":
break
try:
print line
except:
pass
line = raw_input ( "Enter something: " )
line = line.strip()
--------------------------------------------------------------------------- StdinNotImplementedError Traceback (most recent call last) <ipython-input-22-0770a488ab72> in <module>() ----> 1 line = raw_input ( "Enter something: " ) 2 line = line.strip() 3 while True: 4 if line == "" or line == "q": 5 break /usr/local/lib/python2.7/dist-packages/IPython/zmq/ipkernel.pyc in <lambda>(prompt) 343 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) 344 else: --> 345 raw_input = lambda prompt='' : self._no_raw_input() 346 347 if py3compat.PY3: /usr/local/lib/python2.7/dist-packages/IPython/zmq/ipkernel.pyc in _no_raw_input(self) 686 """Raise StdinNotImplentedError if active frontend doesn't support 687 stdin.""" --> 688 raise StdinNotImplementedError("raw_input was called, but this " 689 "frontend does not support stdin.") 690 StdinNotImplementedError: raw_input was called, but this frontend does not support stdin.
var_1 = True
var_2 = False
type( var_1 )
bool
var_1 and var_2
False
var_1 or var_2
True
not var_1 or var_2
False
More on lists here
a_string = "1 2 3" # This is just a string
type ( a_string ) # Test that it is indeed a list
str
type ( a_string.split() ) # Split a string to create a list of elements...
list
A Python list is an ordered arrangement of elements. Note that the elements can have different types.
Lists are defined either using the list
keyword or using []
my_list = [ 1, 2, "three", "four", "5" ] # A list. In this case, an mix of ints and strs
type ( my_list ) # Check the type
list
In Python, lists start at 0, and we refer to the elements using [i]
, where i
is the element number
print my_list [0] # Print the first element
1
print my_list [3] # The fourth element
four
print my_list [ 0:2] # Select from first to third element (non-inclusive)
[1, 2]
print my_list [0:4:2]# Select from 0 to 4, skipping every other element
[1, 'three']
print my_list [ -1 ] # -1 is the last element
5
print my_list [ :-3] # Select from element 0 (ommitted) to third from the end
[1, 2]
print my_list [-3:] # Select from 3rd element from the end to end (ommitted)
['three', 'four', '5']
help(list) # or see [this](http://docs.python.org/tutorial/datastructures.html#more-on-lists)
Help on class list in module __builtin__: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __delitem__(...) | x.__delitem__(y) <==> del x[y] | | __delslice__(...) | x.__delslice__(i, j) <==> del x[i:j] | | Use of negative indices is not supported. | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __gt__(...) | x.__gt__(y) <==> x>y | | __iadd__(...) | x.__iadd__(y) <==> x+=y | | __imul__(...) | x.__imul__(y) <==> x*=y | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __mul__(...) | x.__mul__(n) <==> x*n | | __ne__(...) | x.__ne__(y) <==> x!=y | | __repr__(...) | x.__repr__() <==> repr(x) | | __reversed__(...) | L.__reversed__() -- return a reverse iterator over the list | | __rmul__(...) | x.__rmul__(n) <==> n*x | | __setitem__(...) | x.__setitem__(i, y) <==> x[i]=y | | __setslice__(...) | x.__setslice__(i, j, y) <==> x[i:j]=y | | Use of negative indices is not supported. | | __sizeof__(...) | L.__sizeof__() -- size of L in memory, in bytes | | append(...) | L.append(object) -- append object to end | | count(...) | L.count(value) -> integer -- return number of occurrences of value | | extend(...) | L.extend(iterable) -- 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) -- remove first occurrence of value. | Raises ValueError if the value is not present. | | reverse(...) | L.reverse() -- reverse *IN PLACE* | | sort(...) | L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; | cmp(x, y) -> -1, 0, 1 | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T
my_list = [ "twinkle", "little" ]
my_list.insert ( 0, my_list[0].capitalize() )
my_list.append ( "star" )
print my_list
['Twinkle', 'twinkle', 'little', 'star']
my_list = [ "twinkle" ] *2 + "little star".split()
print my_list
['twinkle', 'twinkle', 'little', 'star']
print [ ( s== "star" and "bat" ) or s for s in my_list]
['twinkle', 'twinkle', 'little', 'bat']
extra=" How I wonder what you are"
my_list.extend ( extra.split() )
print my_list
['twinkle', 'twinkle', 'little', 'star', 'How', 'I', 'wonder', 'what', 'you', 'are']
my_list.remove ( "you")
print my_list
['twinkle', 'twinkle', 'little', 'star', 'How', 'I', 'wonder', 'what', 'are']
my_list.insert ( -1, "ur" )
my_list.pop ( -1 )
print my_list
['twinkle', 'twinkle', 'little', 'star', 'How', 'I', 'wonder', 'what', 'ur']
len ( my_list )
9
Use .join()
to join the elements of my_list
above into a single string again.
print "1" + "1"
print 1 + 1
11 2
i = 1
print i
1
i += 1
print i
2
i = i + 1
print i
3
i *= 2
print i
6
i = i*2
print i
12
i = i/2
print i
6
i = i + 1
print i/2 ###!!!
3
print i/2, i % 2
3 1
print "This is an integer: %d" % ( i )
This is an integer: 7
print "This is the same integer: %03d" % ( i )
This is the same integer: 007
print 3.0/2
1.5
print "%21.10f" % ( 1.0e10 + 1e-6)
10000000000.0000019073
Dictionaries are similar to lists, but in this case, the different elements are unordered and are accessed by keys, rather than by position.
my_dict = { "key1": "something", "key2": "other", "key3":150. }
print my_dict
{'key3': 150.0, 'key2': 'other', 'key1': 'something'}
print my_dict[ "key1" ]
something
The keys can be strings, integers, tuples... We can also nest dictionaries inside dictionaries:
some_other_dict = { "older_dict": my_dict, "some_key": 42 }
print some_other_dict
{'older_dict': {'key3': 150.0, 'key2': 'other', 'key1': 'something'}, 'some_key': 42}
my_dict[ "key3" ] = my_dict[ "key3" ]*3
print some_other_dict
{'older_dict': {'key3': 450.0, 'key2': 'other', 'key1': 'something'}, 'some_key': 42}
my_dict[ "key2" ] = None
print some_other_dict
{'older_dict': {'key3': 450.0, 'key2': None, 'key1': 'something'}, 'some_key': 42}
modis_bands = ['630-690','780-900','450-520','530-610','1230-1250','1550-1750','2090-2350']
band_numbers = range ( 1, len( modis_bands ) + 1 )
modis = dict ( zip ( band_numbers, modis_bands ) )
for i, m in modis.iteritems(): # Also itervalues, iterkeys, etc...
print i, m
1 630-690 2 780-900 3 450-520 4 530-610 5 1230-1250 6 1550-1750 7 2090-2350
File access requires to
Let's start defining some data...
the_data = [[1.,2.,3.,4.,5.],[1.,4.,9.,16.,25.]]
print the_data
print len ( the_data )
print len ( the_data[0] ), len ( the_data[1] )
[[1.0, 2.0, 3.0, 4.0, 5.0], [1.0, 4.0, 9.0, 16.0, 25.0]] 2 5 5
output_file = open ( "temporary_file.txt", 'w' )
for i in range ( len( the_data[0] ) ):
output_file.write ( "%f %f\n" % ( the_data[0][i], the_data[1][i] ) )
output_file.close()
You can now use less
(or more
) to view the contents of the file temporary_file.txt
. It should contain the following:
1.000000 1.000000
2.000000 4.000000
3.000000 9.000000
4.000000 16.000000
5.000000 25.000000
input_file = open ( "temporary_file.txt", 'r' )
input_data = input_file.readlines()
print input_data
['1.000000 1.000000\n', '2.000000 4.000000\n', '3.000000 9.000000\n', '4.000000 16.000000\n', '5.000000 25.000000\n']
data = []
values = []
for i in xrange ( len ( input_data ) ):
the_line = input_data[i].strip().split()
data.append ( float ( the_line[0] ) )
values.append ( float ( the_line[1] ) )
new_data = [ data, values ]
print "new_data: ", new_data
print "the_data: ", the_data
print "Are they equal?", new_data == the_data
new_data: [[1.0, 2.0, 3.0, 4.0, 5.0], [1.0, 4.0, 9.0, 16.0, 25.0]] the_data: [[1.0, 2.0, 3.0, 4.0, 5.0], [1.0, 4.0, 9.0, 16.0, 25.0]] Are they equal? True