String operation in Python

✓ A string is a sequence of characters.

>>> fruit = 'banana'
>>> print fruit[1]
a
>>> print fruit[0]
b
>>> print len(fruit)
6
>>> print fruit[length]
IndexError: string index out of range
>>> print fruit[length-1]
a
#Traversal with a for Loop
index = 0
while index < len(fruit):
    letter = fruit[index]
    print letter
    index = index + 1

for char in fruit:
   print char
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python
>>> fruit = 'banana'
>>> print fruit[:3]
'ban'
>>> print fruit[3:]
'ana'

✓ String searching operation

def find(word, letter):
    index = 0
    while index < len(word):         
        if word[index] == letter:             
            return index         
        index = index + 1     
    return -1 

>>> word = 'banana'
>>> print word.find('a')
1
>>> print word.find('na')
2

✓ in Operator

>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s