String Methods in Python

There are several string methods that come built-in with Python 2.0 and above. These are operations that help you to manipulate strings or gather some information from these strings. These methods play a very big role while writing programs that involve text processing. 

The general syntax of using a method in strings is as follows.
string.method(arg1,arg2..(…)), where string is the name of the string and arg1, 
arg2 are arguments passed by method titled method of that string.
We will check the different methods in a string according to alphabetic order of
the strings. Some of these methods are new to users of Python 2.1 and lower.
  • This is not a complete list of built-in methods of strings in Python. Since certain methods require discussion on certain other topics not quite under the limits of this article, they are not discussed here.

capitalize(     )

The method capitalize() returns a copy of the string with only its first 
character capitalized. Here is an example.

>>> x='string'
>>> x.capitalize()
'String'

center(width)

The method center has an argument called width, which returns the 
string centered over the width. The argument width is an integer, and the padding
either side is done using spaces. Here is an example.

>>> x.center(10)
'  string  '#there is  padding of two spaces either side of the string.

count(            sub, startindex, stopindex)

The method count returns number of occurrences of a sub string within a string. 
It returns the number of occurrences as an integer. You can use count to even
check within a slice of a string. However unlike the slice method where you enter
the indexes in square brackets with a colon in between, here you simply write down
the index of the first element in the substring  (startindex) and the index of the last
element (stopindex) separated by commas.

>>> y='floccinaucinihilipilification'
>>> y.count('i')
9
>>> y.count('n',1,22)
2

endswith(suffix)

The method endswith returns True if the string ends with a specific suffix or else 
false. You can use it to compare the slice of a string too. True or false is
displayed usually by returning 1 or 0.

>>> y.endswith('ion')
1 # It is true

expandtabs(            [tabsize])

This method returns a copy of the string where all tab characters are 
expanded using spaces. If no specific value is given to tabsize, a tab size of 8 
characters is assumed.  See the example below.

>>> z='Jack   and     Jill'

>>> z.expandtabs(19)
'Jack               and                 Jill'

find(    sub,firstindex, lastindex)

This method returns the lowest index in the string where sub-string sub is found. 
Incase the sub string is not found it returns -1

>>> y.find('ih')
12

index(sub, firstindex, lastindex)

This method works just like find, but it raises a ValueError when the sub-string 
is not found.

isalnum()

This returns true if all characters in a string are alphanumeric. Even if one 
character is not alphanumeric, it returns a negative answer.

>>> a='22python'
>>> b='22python/'
>>> a.isalnum()
1
>>> b.isalnum()
0

isalpha(         )

Just like the isalnum(), isalpha() returns true if all the characters of the 
string are alphabetical. It returns false if at least one is found not be an alphabet.

>>> a.isalpha()
0

isdigit(           )

This returns true if there are only integers and false otherwise. 

islower(         )

This method returns true if all characters in the string are lowercase and in case 
there is a character that is not a lowercase, it returns False.

>>> a='22python'
>>> a.islower()
1

isspace(        )

The method returns true if there are only white-space characters in the string 
and if the string is not empty.

istitle( )

This method returns true if the string is a title-cased string. In a title case, 
the first letter of each word is capitalized, and rest of each word is in lower cases.

>>> title='The Bourne Identity'
>>> title.istitle()
>>> 1

isupper(        )

This method is the exact reverse of islower(), and returns true if all cased 
characters in the string are uppercase and false even if one character is lower case.

join(seq)

This method returns a string, which is the concatenation of the strings in the 
sequence seq. The separator between elements is the string providing this method.

>>> j='at'
>>> t=('r','s','p','m','c','b')
>>> j.join(t)
'ratsatpatmatcatb'

ljust(   width)

The method returns the string left justified in a string of length width. 
Padding is done using spaces. The method rjust does the exact reverse.
The original string is returned if width is less than length of the string.

lower()

This method returns a copy of the string converted to lowercase. 

>>> M='ABC'
>>> M.lower()
'abc'

lstrip(      chars) 
This method has seen a minor metamorphosis since Python ver 2.2.2. This returns 
a copy of the string , with the leading characters removed. If argument chars is
omitted it returns only white space characters if any are removed.

>>> y.lstrip('fl')
' occinaucinihilipilification'

replace(         old, new)

This returns a copy of the string with all occurrences of sub-string old replaced by new. 
Check the example below.

>>> y.replace('i','e')
'floccenaucenehelepelefecateon'

rfind(sub, firstindex, lastindex)

This method is like find() but returns the highest index of the sub-string within a 
string. The method on failure returns –1.

>>> y.rfind('i')
26

rindex(           sub, firstindex, lastindex)

This method does just the same as rfind(), but returns a Value Error instead of –1  
if the condition is false.

rstrip( chars)

This returns a copy of the string with trailing characters removed. If argument 
chars is omitted just white-space characters are removed. The characters will be
stripped from end of the line. It is almost antonymous with lstrip.

split(   sep, maxsplit)

This returns a list of the words in the string, using sep as the delimiter string. 
If argument maxsplit is provided, at most maxsplit number of splits is done.
If sep is not specified or is set to None, any white-space string is a separator.

>>> y.split('i',4)
['flocc', 'nauc', 'n', 'h', 'lipilification']

Splitlines(     [keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are 
not included in the resulting list unless keepends is given and true.

startswith(    prefix, startindex, endindex)

This is similar to endswith except that it returns True if string starts with the 
prefix, otherwise return false.

>>> H='The cat ate dog'
>>> H.startswith('The')
1

strip(chars)

This returns a copy of the string with leading and trailing characters removed. 
If chars is omitted or None, white-space characters are removed. This again has been
introduced with Python version 2.2.2.

swapcase()

This method returns a copy of the string with all characters toggled as explained 
in the example below.

>>> toggle='American Beauty'
>>> toggle.swapcase()
'aMERICAN bEAUTY'

title()

This method returns the title-cased version of the string. The example below is 
self-explanatory.

>>> title1='the bridges of madison country'
>>> title1.title()
'The Bridges Of Madison Country'

upper(            )

The reverse of the lower()method, this returns  a copy of the string converted to 
uppercase. This is illustrated below

>>> x.upper()
'STRING'

 

zfill(     Width)

This method returns the numeric string left filled with zeros in a string of length 
width. The original string is returned if width is less than the length of the string.

>>> x.zfill(10)
'0000string'

You can use the different string methods and functions while writing some very useful 
programs. There are several areas where string processing is useful. One of the fastest
growing technologies vertical is BioInformatics, where computers are used for research
in Bio Sciences.
One of the very elementary problems Biotech scientists face is in handling the DNA 
strings. The DNA strings are strings of letters. Usually these strings run to thousands
of lines of code.

           
file DNAStringchange.py
def change(s,old,new):
if s.isalpha()==1:
return s.replace(old,new)
else:   
return'Enter the DNA string again, there seems to be error'

>>> s='CCGTCAAACGT'
>>> change(s,'T','A')
'CCGACAAACGA'

Yet another example can be a series of if..elif..else loops that checks for
conditions for a good password. The conditions for a good password include

It should contain between 6 and 15 characters
It should have at least one special character
It must not contain spaces
It must  have at least one lower cased and one upper cased character.
It should have at least one numeral.

The code below sums up all the conditions above and implements the rules for a good password checking program.

goodpassword.py
def goodpassword(x):
y=len(x)
if y<5 or y>16 ==0:
return 'Length of password should be between 6 and 15'
elif x.isdigit()or x.isalpha()==1:
return 'Have at least one number and one alphabet'
elif x.islower() or x.isupper()==1:
return ‘Have both lower and upper cases'
elif x.isalnum()==1:
return’ Have at least one special character'
elif x.count('')==1:
return ‘No spaces allowed'
else:
return'Password accepted'








}