Monday, March 18, 2013

Strings in Python

Before you read my stuff have a look at official documentation.Get some vague idea and come back here.
Check the pleac project...I love that site,last but not least tutorials point,even then you don't understand you're in right place. :)).

1.Introduction to strings.



#!usr/bin/env/python
###############################################################################
mystr = "\n"        #a new line character.

mystr_raw=r"\n"     #two characters,\ and n.
print mystr_raw 
print "Length of mystr_raw:",len(mystr_raw),'\n'

###############################################################################
mystr_dq="Matthew 'Mark' Luke" #Single quote inside double quote.
print mystr_dq+"\n"            #'+' is used for adding(concatenating the strings.)

mystr_sq='Matthew "Mark" Luke' #dq(double quote) inside sq(single quote).
print mystr_sq+"\n"           

################################################################################
mystr_1_multiplelines="""These examples are
taken from pleac project.Really inspiring"""    #used triple double quotes.
print mystr_1_multiplelines+'\n'

mystr_2_multiplelines='''These examples are     
taken from pleac project.Really inspiring'''    #used triple single quotes.
print mystr_2_multiplelines+'\n'
################################################################################


Output:

\n
Length of mystr_raw: 2
Matthew 'Mark' Luke
Matthew "Mark" Luke
These examples are
taken from pleac project.Really inspiring
These examples are
taken from pleac project.Really inspiring



2.String Slicing.


#!usr/bin/env/python
"""Python strings are immutable once created they cann't be modified"""
mystr="Python is awesome!!!!"#P(0 or -21) y(1 or-20) t(2 or 19)....awesome(10,11,12,13,14,15,16 or -11,-10...-5 )
#     +012345678901234567890  Indexing forwards  (left to right)
#      109876543210987654321- Indexing backwards (right to left)
print'Printing..the full string ===>',mystr +'\n'

print mystr[0] +'\n'  #using forward indexing to print 'P'.
#Output:P
print mystr[-21]+'\n' #using backward indexing to print 'P'
#Output:P
print mystr[-1],mystr[len(mystr)-1]+'\n' #length=21,Since indexing is started at 0 we'll have one less 
#len(mystr)=lenght of the string.
""" 
mystr[a:b]
Case 1:Forward Indexing 
0<=a<b<=(len(mystr)-1)
mystr[a:b]==>Start from a till b-1
mystr[:b]==>assume a=0,start from a till b-1
mystr[a:]==>start from a till end.
Case2:Backward Indexing===>here we are using negative numbers,So do look
at couple of examples.
-len(mystr)<=a<b<=-1
"""
print mystr[0:5]+'\n' #start from 0 to 5-1==>(Pytho)
print mystr[1:]+'\n'  #start from one till end==>(ython is awesome!!!!)
print mystr[:18]+'\n' #start from 0 to 18-1==>(Python is awesome!)
print mystr[-20:-5]+'\n'#start from -20 till -5==>(ython is awesom)
#mystr[-5:-20] will return an empty string.
print mystr[-5:]+'\n' #start from -5(e) till end(!)===>(e!!!!)
print mystr[:-18]     #start from -21 till (-18-1=-19)===>(Pyt)

mystr = mystr[:9] + " easier than C" + mystr[17:]
print mystr
 

Output: 

Printing..the full string ===> Python is awesome!!!!
P
P
! !
Pytho
ython is awesome!!!!
Python is awesome!
ython is awesom
e!!!!
Pyt
Python is easier than C!!!!

3.String Methods.

 
#!usr/bin/env/python
"""String Methods """

mystr="Try 'import this' in your python interpreter"
print mystr.count('in')
#Counts number of occurences of 'in'.
#Output:2 
print mystr.find('i') # index of first occurence of i==&gt;5('i' in import)
print mystr.find('in')#index of first occurence of in==&gt;18(returns position of i in in i.e 18)
print mystr.find('in',19)#start from 19 and find first occurence of in
#There's an 'in' in interpreter.
print "Ajay".find('a')
#Output is 2

print "AJAY".lower()
#Return a copy of AJAY, but with upper case letters converted to lower case.
print "ajay".upper()

print mystr.replace("import this","import string")
#Dude strings do not change in python....but what happened right now?? It just return a copy of mystr.

print mystr
#mystr is same unmodified.

import string  #All string methods can be done like this.Try lower,upper and find in the simlar way.
print string.replace(mystr,"import this","import string")

"""Below are some useful oneline methods.
Replace str with a variable mystr or strings like "Ajay is dumb"."""

# str.capitalize()
print mystr.capitalize()
"""Return a copy of the string with its first character capitalized and the rest lowercased."""

"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""

#str.split()==&gt;Creates a list.

print "Ajay is dumb,idiot,mining engineer".split()
#Split after a whitespace(space)
#Output:['Ajay', 'is', 'dumb,idiot,mining', 'engineer']

print "Ajay is dumb,idiot,mining engineer".split(',')
#splits after a coma ',' and forms a list of words.
#Output:['Ajay is dumb', 'idiot', 'mining engineer']

print "Ajay is dumb,idiot,mining engineer".split(None,1)
#None is nothing but your telling to split after whitespace.but number of splits should be one.
#In place of None you can use ',' or anything.In place of 1 you can use any number
"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.strip()
#Return a copy of the string with the leading and trailing characters removed.
print "    Ajay loves space(white space)   ".strip()
#Output:Ajay loves space(white space)
print 'www.example.com'.strip('cmowz.')
#Output:example
#??? What happened let's try some more examples.
print 'www.example.com'.strip('cmoz.')
#Output:www.example
#'cmoz.'==&gt;'.comz'===&gt;'.com' can be removed because it's in a sequence.z is ignored.
print 'www.example.com'.strip('cmz.')
#Output:www.example.co
#'.cmz'==&gt;'m'==&gt;So m is removed.
"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.join
seq = ['1','2','3','4','5']   #'1','2'....are strings.
print '+'.join(seq)
#Output:1+2+3+4+5

print '*_*'.join("Ajay's blog is the dumbest".split())
#Output:Ajay's*_*blog*_*is*_*the*_*dumbest
#Just combined the split and join.To understand this first we did a split on the string.
# 1)"Ajay's blog is the dumbest".split() 
#2)later i joined the list elements using str.join

"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.partition
print("Python programmers are awesome :) ".partition('are'))
#Output:('Python programmers ', 'are', ' awesome :) ')
#It's gives a tuple of 3 elements.
#1)Everything before the partition element==&gt;here it's "Python programmers"
#2)Partition element itself.===&gt;'are'
#3)Everything after Partition element.==&gt;'awesome'

#Check out the original documentation for more examples and methods. 

Output:
2
5
18
33
2
ajay AJAY
Try 'import string' in your python interpreter
Try 'import this' in your python interpreter
Try 'import string' in your python interpreter
Try 'import this' in your python interpreter
['Ajay', 'is', 'dumb,idiot,mining', 'engineer']
['Ajay is dumb', 'idiot', 'mining engineer']
['Ajay', 'is dumb,idiot,mining engineer']
Ajay loves space(white space)
example
www.example
www.example.co
1+2+3+4+5
Ajay's*_*blog*_*is*_*the*_*dumbest
('Python programmers ', 'are', ' awesome :) ')

Check out the questions from SO,some day you gonna be same place so practice them.One more i missed here is string formatting,translate method which are important.I'll be posting when i'm free :)).

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment