I’m Learning Python (part 5)

I’m Learning Python (part 5)

Python Logo

String Is Immutable?

Last time I told you to try to change a specified character, you must have failed if you tried:
>>> s[0] = ‘c’
The error you’d get is:
TypeError: ‘str’ object does not support item assignment
This means that strings are immutable, so are core-types, numbers and tuples, they can’t be changed, while lists and dictionaries can be changed freely.

More Methods?

All the previous methods and operations are sequence operations, but strings have more methods:
>>> s = ‘My Text’
>>> s.find(‘Tex’ ) #returns the index of the first occurrence of the parameter
>>> s.find(‘abc’ ) #if the parameter wasn’t found it will return -1
>>> s.replace(‘Text’, ‘Code’ ) #replaces every occurrence of the first parameter with the second one ‘My Code’ >>> s #notice that the string hasn’t changed
‘My Text’
>>> s = ‘aa,bb,cc,dd’
>>> s.split(‘,’ ) #splits the string into a list of values separated with the parameter
[‘aa’, ‘bb’, ‘cc’, ‘dd’]
>>> s =’My Text\n’
>>> s.rstrip() #removes white space characters from the right of the string
‘My Text’
>>> s #don’t forget that the string hasn’t changed 😉
‘My Text\n’
>>> len(s) #returns the length of the string
>>> ord(‘\n’ ) #returns the ASCII code for the given character
>>> s = ‘MyTextA’ # is the null character though it doesn’t terminate the string ?
>>> len(s)
>>> s

Wanna Get More?

Of course I can’t talk about every method for every type, but I’ll give you a simple way to get more, in Python there is a method called “dir” which lists the object’s methods and properties:
>>> dir(s)
[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__doc__’, ‘__eq__’, ‘__format__’, __ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__getslice__’, ‘__gt__’, __hash__’, ‘__init__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, __reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, __sizeof__’, __str__’, ‘__subclasshook__’, ‘_formatter_field_name_split’, ‘_formatter_parser’, ‘capitalize’, center’, ‘count’, ‘decode’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘index’, isalnum’, isalpha’, ‘isdigit’, ‘islower’, ‘isspace’, ‘istitle’, ‘isupper’,’join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘partition’, replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]
Don’t care about those who has underscores, but the rest are methods.
Now to know more about a specified method you can use the “help” method:
>>> help(s.count)
Help on built-in function 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.

What About Regular Expressions?

Users with a background about regular expressions will definitely ask about it, and the answer is yes you can use them with strings:
>>> import re
>>> match = re.match(‘Hello[ \t]*(.*)world’, ‘Hello Python world’ )
>>> match.group(1)
>>> match = re.match(‘/(.*)/(.*)/(.*)/’, ‘/usr/lib/bin/’ )
>>> match.groups()
(‘usr’, ‘lib’, ‘bin’ )
Of course you can do more as you know with regular expressions like replacing and splitting, try “dir” and “help” for more 😉

What Is The Difference Between ‘Text’ And “Text”?

There is no difference at all, but there is a third way to write strings:
>>> s = “””Text”””
This way preserves the text formatting, which means you can write:
>>> s = “””
<b>’I Love “Python”‘</b>
>>> s
‘\n<html>\n<head></head>\n<body>\n<b>’I Love “Python”‘</b>\n</body>\n</html>\n’
You can use this way to write pre-formatted text just like XML and HTML.

Lists And Sequences:

Lists are sequences like strings and they support every thing we talked about when discussed strings methods but the difference is that the results of methods are lists instead of strings, and that lists are changeable objects which means they support changing in place:
>>> L = [123, ‘mpcabd’, 1.23] #lists support multi-types 🙂
>>> len(L)
>>> L[0]
>>> L[-1]
>>> L[:-1]
[123, ‘mpcabd’]
>>> L + [4, 5, 6]
[123, ‘mpcabd’, 1.23, 4, 5, 6]
>>> L
[123, ‘mpcabd’, 1.23]
Lists are so much like arrays but they have no fixed size, so you can append to them and delete from them:
>>> L.append(111)
>>> L
[123, ‘mpcabd’, 1.23, 111]
>>> L.pop(0)
[‘mpcabd, 1.23, 111]
You can even sort and reverse them:
>>> L = [‘a’, ‘z’, ‘c’]
>>> L.sort()
>>> L
[‘a’, ‘c’, ‘z’]
>>> L.reverse()
[‘z’, ‘c’, ‘a’]
To find more try “dir” and “help” 🙂

What abound boundaries?

Try the following and you’d see an error:
>>> L = [‘a’, ‘b’, ‘c’]
>>> L[9]
IndexError: list index out of range
This means that Python checks for boundaries not like C and C++.

Can I Nest Lists?

Yes 😀
>>> M = [
[ 7, 8, 9 ]
>>> M
>>> M[1] [4, 5, 6]
>>> M[1][2]
This is a good way to define matrices, but I advise you to use NumPy for mathematical operations, ‘cuz it is optimized for fast use.

What Are List Comprehensions?

Python includes along with what we’ve discussed a powerful methods called “List Comprehension Expressions”, suppose we wanna extract the second column of our previous matrix (M), what would you do? Python provides a good way:
>>> col2
[2, 5, 8]
Not good enough? Take this:
[3, 6, 9]
[2, 8]
Not enough yet? Take this one and take a nap 🙂
>>> [M[i][i] for i in [0, 1, 2]]
[1, 5, 9]
Not enough? I’ll kill you then 😈
For more wait for me to study 🙂

Bottom Line:

I’m sorry I was late this time but I’m really having a busy phase @ work, please wait for more and don’t get bored.


Leave a Reply