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]
def alternate(string): print string[0::2] # print alternate letters starting from 0 print string[1::2] #print alternate letters starting from 1
alternate("ABCD123")#call the above "function"
alternate("I am a good girl")
Ia odgr mago il
Ex2: Writing in reverse
"Hello World"[::-1] #last index -1 reverses the order of the sentence! basically it reads, #start from 0 to end by going negative steps
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
string = "I am a String" character='A' multiple_string = """I am multiple line String ! I am line 2! Hey I am line3 """
'I am a String'
'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
'I am a StringI am a String'
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
str1 = "String1" str1[:-1]# all but the last letter(called slicing)
str1 #str1 remains the same
str = str1[:-1]#save it to a new variable
str1 = str1[:-1] # or reassign to same variable name , #when you dont need the previous sentence anymore in future
str1# str1 is changed to "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)
string = "Count the number of eee's in me."
length = len(string) # number of "letters", including space and punctuations in the sentence!save it to variable length
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!
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!
"Count the number of eee's in me."
string.count('e') # do the same thing (count no of occurrences) # as above but this time it is inbuilt
string.find('e')# find the "first" occurance of the letter in the string
string.lower()# convert everthing to lower case
"count the number of eee's in me."
string.upper()# convert everthing to upper
"COUNT THE NUMBER OF EEE'S IN ME."
string.replace('e','_')# replace all occurrences with some other values
"Count th_ numb_r of ___'s in m_."
" abcd ".strip()#removes "spaces" from lead or end
string.split(' ')#split sentence into words by "space" = " "
['Count', 'the', 'number', 'of', "eee's", 'in', 'me.']
Now let us count the total number of vowels in a sentence
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
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”
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”
#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”)