Sunday, June 19, 2011

Strings

Python has a built-in String class named "str".String literals can be enclosed in single or double quotes.
Consider for example:
>>> print "hai friend \n are you fine"
hai friend
are you fine

Suppose we want to get \n, \t etc in our sentence we have to add r before the quotes.
>>> print r"hai friend \n are you fine"
hai friend \n are you fine

There are a number of operations on strings.
Concatenation is done with the + operator.
>>> "hi"+" friend"
'hi friend'

Suppose we want to concatenate a string with a number, we can convert number to a string with the str casting function, otherwise,
>>> pi=3.14
>>> text='The value of pi is '+pi
Traceback (most recent call last):
File "", line 1, in
TypeError: cannot concatenate 'str' and 'float' objects

So we can concatenate these by,
>>> pi=3.14
>>> text='The value of pi is '+str(pi)
>>> text
'The value of pi is 3.14'

The * operator between strings and numbers creates a new string that is a number of repetitions of the input string.
>>> print 3*"cool !"
cool !cool !cool !


Comparing Strings:
Strings can be compared with the standard operators :
==, !=, <, >, <=, and >=.


String methods

s.lower,s.upper -returns the lowercase or uppercase version of the string.
s.startwith('other'),s.endwith('other') - tests if the string start with or end with the given other string
s.find('other') - searches for the given other string and returns the first index where it begins.Otherwise return -1.
s.replace('old','new') - returns a string where all occurences of 'old' have been replaced by new.

Extracting substrings: Strings in Python can be subscripted just like an array: s[4] = 'a'. Two indices separated by a colon, will return a substring containing characters index1 through index2-1. Indices can also be negative, in which case they count from the right, i.e. -1 is the last character. Thus substrings can be extracted like,
>>> s="beautiful"
>>> s[1:4]
'eau'
>>> s[:5]
'beaut'
>>> s[3:]
'utiful'
>>> s[-7:-2]
'autif'

String % : Python has % operator which takes a printf-type format string on the left (%d,%s),and matching values separated by commas.
>>> text="%d little girls are dancing with their %s"%(3,"mother")
>>> text
'3 little girls are dancing with their mother'

No comments:

Post a Comment