Inspecting Strings


In [11]:
# This is some IPython %magic
%xmode plain


Exception reporting mode: Plain

In [2]:
len("hello")


Out[2]:
5

In [1]:
"hello" + "!"


Out[1]:
'hello!'

In [3]:
"l" in "hello"


Out[3]:
True

In [4]:
"hello"[-3:]


Out[4]:
'llo'

Formatting Strings


In [12]:
# Busted
count = 3
"Number of items: " + count


Traceback (most recent call last):

  File "<ipython-input-12-f76e725a32aa>", line 3, in <module>
    "Number of items: " + count

TypeError: cannot concatenate 'str' and 'int' objects

In [9]:
# OK, but there's a better way
name = "Peter"
greeting = "Hello"
"%s, %s, what's happenning?" % (greeting, name)


Out[9]:
"Hello, Peter, what's happenning?"

In [13]:
"{}, {}, what's happenning?".format(greeting, name)


Out[13]:
"Hello, Peter, what's happenning?"

In [18]:
print "Number of items: ---{:05}---".format(count)
print "Number of items: ---{:>5}---".format(count)
print "Number of items: ---{:<5}---".format(count)


Number of items: ---00003---
Number of items: ---    3---
Number of items: ---3    ---

Joining and Splitting


In [26]:
from string import ascii_lowercase
print ascii_lowercase
a_f = list(ascii_lowercase[:6])
print a_f
letters = ", ".join(letters)
print letters


abcdefghijklmnopqrstuvwxyz
['a', 'b', 'c', 'd', 'e', 'f']
a, b, c, d, e, f

In [28]:
letters.split(", ")


Out[28]:
['a', 'b', 'c', 'd', 'e', 'f']