Strings

Indexing

In [1]:
greet = "Hello Bob"
In [3]:
greet[0]  # string indexing
Out[3]:
'H'
In [4]:
print(greet[0], greet[2], greet[4])
H l o
In [6]:
idx = int(input("Please enter a string position:"))
print(greet[idx])
Please enter a string position:7
o
In [7]:
idx = int(input("Please enter a string position:"))
print(greet[idx])
Please enter a string position:100
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-99ccf73069c7> in <module>()
      1 idx = int(input("Please enter a string position:"))
----> 2 print(greet[idx])

IndexError: string index out of range
In [8]:
x = 8
print(greet[x - 2])
B
In [9]:
print(len(greet))
9
In [10]:
print(list(range(len(greet))))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
In [12]:
for i in range(len(greet)):
    print(i, greet[i])
0 H
1 e
2 l
3 l
4 o
5  
6 B
7 o
8 b

Indexing in Reverse

In [14]:
greet[len(greet) - 1]
Out[14]:
'b'
In [15]:
greet[len(greet) - 2]
Out[15]:
'o'
In [16]:
greet[len(greet) - 3]
Out[16]:
'B'
In [17]:
greet[-1]
Out[17]:
'b'
In [18]:
greet[-2]
Out[18]:
'o'
In [19]:
greet[-3]
Out[19]:
'B'

Slicing

In [20]:
greet[0:3]
Out[20]:
'Hel'
In [21]:
greet[5:9]
Out[21]:
' Bob'
In [22]:
greet[:5]
Out[22]:
'Hello'
In [23]:
greet[5:]
Out[23]:
' Bob'
In [24]:
greet[:]
Out[24]:
'Hello Bob'
In [25]:
greet[15]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-25-f7011278f173> in <module>()
----> 1 greet[15]

IndexError: string index out of range
In [26]:
greet[5:15]
Out[26]:
' Bob'
In [30]:
greet[8:5]
Out[30]:
''
In [31]:
greet[8:5:-1]
Out[31]:
'boB'
In [34]:
greet[-3:-1]
Out[34]:
'Bo'
In [37]:
greet[-3:0]
Out[37]:
''
In [38]:
greet[-3:]
Out[38]:
'Bob'
In [40]:
s = -3
e = None
greet[s:e]
Out[40]:
'Bob'
In [41]:
greet[-1:-4:-1]
Out[41]:
'boB'

"Arithmetic" Operations on Strings

In [42]:
"foo" + "bar"  # concatenation
Out[42]:
'foobar'
In [43]:
s1 = "foo"
s2 = "bar"
s3 = s1 + s2
print(s3)
foobar
In [44]:
s1 + 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-f90ed9df3b77> in <module>()
----> 1 s1 + 3

TypeError: can only concatenate str (not "int") to str
In [47]:
usd = "$"
val = 100
s1 = usd + str(val)  # Using the 'str' class to convert an int to a string
print(s1)
$100
In [49]:
border = "_+_"
print(border*30)
_+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+__+_

Looping with Strings

In [51]:
i = 0
for c in greet:
    print(i, c)
    i = i + 1
0 H
1 e
2 l
3 l
4 o
5  
6 B
7 o
8 b
In [1]:
s = ""
for c in "foobar":
    s = s + c
In [2]:
print(s)
foobar