Examples for String Manipulation



In [1]:
# putting an r in front of a string makes the string a "byte string" (in Python 2.*)
print("start \testing vs "+r"end \testing")
#notice that \t turns into a tab in the first string

# putting an ur in front of a string makes the string a "Unicode string" (in Python 2.*)
# ur is not valid in Python 3.* because support was restored for explicit Unicode literals (see PEP 414)


start 	esting vs end \testing

In [2]:
g = 'pub'
h = ''.join(['p', 'u', 'b'])
i = '.'.join(['p', 'u', 'b'])
print(g)
print(h)
print(i)

#there is no '.' in 'h' so you get an array with one element
j = h.split('.')
print(j)

k = i.split('.')
print(k)


pub
pub
p.u.b
['pub']
['p', 'u', 'b']

In [3]:
# 'is' is identity testing, '==' is equality testing
print('\"is\" test '+str(g is h))
print('\"==\" test '+str(g == h)+"\n")

#because 'is' is testing id(g) == id(h)
print('id of g: '+str(id(g)))
print('id of h: '+str(id(h))+"\n")

#note that id(g) == id('pub') here but it doesn't have to...
print('id of g:     '+str(id(g)))
print('id of \"pub\": ' +str(id('pub')))


"is" test False
"==" test True

id of g: 62281632
id of h: 63105856

id of g:     62281632
id of "pub": 62281632

In [4]:
j = 'The quick brown fox jumps over the lazy dog.'
k = j.split('quick')
print(k)


['The ', ' brown fox jumps over the lazy dog.']

In [5]:
l = j[0:21]
print(l)


The quick brown fox j

In [6]:
j.index("the")


Out[6]:
31

In [7]:
'Alice' in j


Out[7]:
False

In [8]:
'dog' in j


Out[8]:
True

In [9]:
y=[]
for x in range(10,20):
    y = y + [x]
print(y)


[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]