String Methods in Python
Posted On September 12, 2016 by Rose Mary filed under Programming
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.
The method capitalize() returns a copy of the string with only its first
character capitalized. Here is an example.
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.
' 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.
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.
1 # It is true
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'
'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
index(sub, firstindex, lastindex)
This method works just like find, but it raises a ValueError when the sub-string
is not found.
This returns true if all characters in a string are alphanumeric. Even if one
character is not alphanumeric, it returns a negative answer.
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.
This returns true if there are only integers and false otherwise.
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.
The method returns true if there are only white-space characters in the string
and if the string is not empty.
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'
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.
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.
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.
This method returns a copy of the string converted to lowercase.
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.
replace( old, new)
This returns a copy of the string with all occurrences of sub-string old replaced by new.
Check the example below.
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.
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.
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.
['flocc', 'nauc', 'n', 'h', 'lipilification']
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'
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.
This method returns a copy of the string with all characters toggled as explained
in the example below.
>>> toggle='American Beauty'
This method returns the title-cased version of the string. The example below is
>>> title1='the bridges of madison country'
'The Bridges Of Madison Country'
The reverse of the lower()method, this returns a copy of the string converted to
uppercase. This is illustrated below
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.
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.
return'Enter the DNA string again, there seems to be error'
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.
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'
return’ Have at least one special character'
return ‘No spaces allowed'