Getting to know strings better in Python!

Hey welcome back!
Solutions to previous post questions:
Exercise: 1. define a function which does the following
print alternate letters
print the leftout letters
example : if string = ABCDEF # output : ACE,BDF # Hints :string[0::2]

In [108]:
def alternate(string):
    print string[0::2] # print alternate letters starting from 0
    print string[1::2] #print alternate letters starting from 1
In [109]:
alternate("ABCD123")#call the above "function"
AC13
BD2

In [110]:
alternate("I am a good girl")
Ia  odgr
 mago il

Ex2: Writing in reverse

In [112]:
"Hello World"[::-1] #last index -1 reverses the order of the sentence! basically it reads,
#start from 0 to end by going negative steps
Out[112]:
'dlroW olleH'

So we have seen upto now how we can define strings and access its letters in them. Now things are going to get interesting. We are now going to use “functions” or commands that already the computer knows to manipulate a string and make it do things. But first we need to know what the computer understands right? It might be a bit boring, and I am not going to give it to you all at once, but through tits and bits and you can find help from google as always! So lets define a string and begin playing with it a bit. Lets see how many ways we can define a string in python

In [1]:
string = "I am a String"
character='A'
multiple_string = """I am multiple line
                    String !
                    I am line 2!
                    Hey I am line3
                  """
In [2]:
string
Out[2]:
'I am a String'
In [3]:
character
Out[3]:
'A'
In [4]:
multiple_string
Out[4]:
'I am multiple line\n                    String !\n                    I am line 2!\n                    Hey I am line3\n                  '

O wait, what are those \n? Well computer understands some more letters which humans have no “sound” for. Example, “\n” stands for an “newline”(n for new) , it is basically equivalent of pressing enter! Similarly, “\t” is a tabular space! So in the above example a multiple line string is defined in triple quotes and it automatically takes in “newline” where ever you press “enter”

Ok now lets define some operation on strings. You can “add” two strings just as numerical things by “+” sign.(beware “-” does not work!) you can even multiply a sentence by a number, and it adds the same copy of itself , lets see some example below

In [8]:
string+string
Out[8]:
'I am a StringI am a String'
In [43]:
print "tabs\t"*4
# (the hash is for comment, nothing after 
#this is seen as a command its for you )see the \t after 'tabs'
print "tabs"*4# see the difference. *4 adds
#the sentence 4 times!
tabs	tabs	tabs	tabs	
tabstabstabstabs

Well now strings are immutable, i.e. you cannot change a string that you have defined.So any new changes you make must be saved under a new name to start with, you can also “reassign” the “changed” string to the original! Examples

In [47]:
str1  = "String1"
str1[:-1]# all but the last letter(called slicing)
Out[47]:
'String'
In [48]:
str1 #str1 remains the same
Out[48]:
'String1'
In [52]:
str = str1[:-1]#save it to a new variable 
In [55]:
str
Out[55]:
'String'
In [56]:
str1
Out[56]:
'String1'
In [57]:
str1 = str1[:-1] # or reassign to same variable name ,
#when you dont need the previous sentence anymore in future
In [59]:
str1# str1 is changed to "String"
Out[59]:
'String'

Well now we will digress a little and do some numbers and then come back and use “strings” with a lot more power!
We have seen how we can access each letters of the sentence by the positions. How now about we manually do this scan through each letters and do something with it. Lets first do a simple example, how about counting the number of ‘e’ in a sentence. (BTW, ‘e’ is the most frequently used letter in English)

In [60]:
string  = "Count the number of eee's in me."
In [62]:
length = len(string) # number of "letters", including space and punctuations in the sentence!save it to variable length
In [63]:
length
Out[63]:
32
In [69]:
count_e = 0 # this is my counter, if i find 'e' then i will add 1 to this
for i in xrange(length): # this is called a "loop",  i is like your index finger running across the length of the sentence
    
    if(string[i]=='e'): # check 'if' the letter at ith index is e. "==" checks if it is "equal". single "=" assigns value
        count_e = count_e+1 #if yes add 1 to count_e variable


 #Look carefully how I gave a "tab" in front of if. This is necessary and very important in python loops, to tell what are the 
 # set of instructions one will follow iteratively. Similarly for "if" we need to add in another "tab" to make it clear what are
 # the statements one need to follow if the statement is true!
In [70]:
count_e
Out[70]:
6

Now we will try different functions that are there in python, to do various jobs.BTW caps are important. meaning variable name
A = 2 and a = 2 are different!

In [73]:
string
Out[73]:
"Count the number of eee's in me."
In [79]:
string.count('e') # do the same thing (count no of occurrences)
                #   as above but this time it is inbuilt
Out[79]:
6
In [86]:
string.find('e')# find the "first" occurance of the letter in the string
Out[86]:
8
In [88]:
string.lower()# convert everthing to lower case
Out[88]:
"count the number of eee's in me."
In [92]:
string.upper()# convert everthing to upper
Out[92]:
"COUNT THE NUMBER OF EEE'S IN ME."
In [91]:
string.replace('e','_')# replace all occurrences with some other values
Out[91]:
"Count th_ numb_r of ___'s in m_."
In [100]:
"   abcd  ".strip()#removes "spaces" from lead or end
Out[100]:
'abcd'
In [103]:
string.split(' ')#split sentence into words by "space" = " "
Out[103]:
['Count', 'the', 'number', 'of', "eee's", 'in', 'me.']

Now let us count the total number of vowels in a sentence

In [117]:
sentence = "the quick brown fox jumped over the lazy dog" #define a sentence
length = len(sentence) # length of sentence(no of characters)
count_vowels = 0 # counter for vowels

for i in xrange(length): # same old indexing, get yours hands out!
    
    letter  = sentence[i] #current letter in the sentence
    if(letter =='a' or letter=='e' or letter=='i' or letter=='o' or letter=='u'):
        #check if the letter is "a" or "e" so on....
        count_vowels = count_vowels+1

print "Number of vowels:\t",count_vowels
print "Number of consonants:\t",length - count_vowels
Number of vowels:	12
Number of consonants:	32

Exercise:
A palindrome is a sentence, which when reversed reads the same as its original, other than punctuations and spaces. e.g.
“Was it a car or a cat I saw”
“Rise to vote Sir”

palindromecomics

Write a function to test if a sentence is a palindrome.
If it is a palindrome print “it is a palindrome”
else print “it is not a palindrome”

tips:
def isPalindrome(string):
#remove spaces (hint : strip)
#find reverse String
#check for equality of strings
print “it is a palindrome”

#call the function
isPalindrome(“Rise to vote sir”)

In []:
Advertisements

Any thoughts?

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