String methods in python

Strings in Python provide a number of methods. Let’s have a look at them. These following 10 methods are explained in detail with an example for each.

  1. strip whitespaces
  2. replace substrings
  3. manipulate cases
  4. split strings
  5. join words
  6. isaplha(), isnumeric()
  7. occurrences of a substring
  8. where is the substring?
  9. endswith
  10. string formatting

1. Strip whitespaces

The following methods help remove whitespaces at the left, right or both ends of a string.

  • string.strip() : Strips whitespaces at both ends of the given string.
>>> sentence = '    Python is amazing     '
>>> sentence.strip()
'Python is amazing'
  • string.rstrip() : Strips whitespace at the right end (end) of the string.
>>> sentence.rstrip()
' Python is amazing'
  • string.lstrip() : Strips whitespace at the left end (beginning) of the string.
>>> sentence.lstrip()
'Python is amazing '

2. Replace substrings


  • Input: Two parameters a and b.
  • Output: All instances of a are replaced by b .

This method lets us replace all instances of a character/string to a new character/string.

>>> sentence = '    Python is amazing     '
>>> sentence.strip().replace('a','is')
'Python is ismiszing.'

Stripping and replacing all instances of ‘a’ with ‘is’.

3. Manipulate cases

The following methods manipulate the cases of a string.

  • string.capitalize() : Capitalizes the first letter in the string.
>>> name='john doe'
>>> name.capitalize()
John doe
  • string.lower() : Converts all the characters in the string to lower case.
>>> name='JOHN DOE'
>>> name.lower()
john doe
  • string.upper() : Converts all the characters in the string to upper case.
>>> name='john doe'
>>> name.upper()
  • string.title() : Converts string into title format. (Capitalizes first letter of each word.)
>>> name = 'john doe'
>>> name.title()
John Doe

We can also check whether the given string is already lower case /upper case/title by using the string.islower() , string.isupper() and string.istitle() .

4. Split strings

The split method splits a given string into a list of strings separated at every instance of the given input character/string.

The default separator for this method is a whitespace ' ' .

>>> name = 'John and Jill went up the hill'
>>> name.split() #separates at the whitespace

The separator can be any character of our choice.

>>> mystring = 'abracadabra'
>>> mystring.split('b')
['a', 'racada', 'ra']
>>> mystring.split('c')
['abra', 'adabra']

This method by default, splits the string at all the instances of the separator starting from the beginning.

We can also choose to split the string at the first n instances of the input string.

The following code splits the string only at the first instance of the input string.

>>> mystring.split('b',1)
['a', 'racadabra']

5. Join words

The join method does the opposite of split method. It concatenates all the items in an iterable into one string with a separator in between each item.

>>> mylist = ['Name', 'Age','Gender']
>>> ','.join(mylist) #comma
>>> ' '.join(mylist) #white space
Name Age Gender
>>> '.'.join(mylist) #fullstop
>>> 'a'.join(mylist) #join with a

6. Alphabets, Numbers or both?

These methods check whether the string satisfies a specific condition.

  • string.isnumeric() : Returns True if all the characters in the string are numbers. Returns False otherwise.
>>> string = '43252345'
>>> string.isnumeric()
>>> string = 'ad323h'
>>> string.isnumeric()
>>> string = '123 245'
>>> string.isnumeric()

Note that whitespace is also a character, which is not a number. Hence, it returns False .

  • string.isalpha() : Returns True if all the characters are alphabets, False otherwise.
>>> string = 'asdfghjkl'
>>> string.isalpha()
>>> string = 'fasdfe134'
>>> string.isalpha()
>>> string = 'asdf ghjkl' #contains whitespace. Returns False
>>> string.isalpha()
  • string.isalnum() : Returns True if the string contains only alphabets or numbers or both, False otherwise.
>>> string = 'asflq1234'
>>> string.isalnum()
>>> string = 'weft 123' #contains whitespace. Returns False
>>> string.isalnum()
>>> string = 'lweiufba'
>>> string.isalnum()

7. Occurrences of substring

The count method counts the number of instances of the input string in the main string.

This method requires only one parameter to run. However, it takes two optional parameters:

  • substring : The string whose count is to be found.
  • start (optional) : The start index in the string where the search starts.
  • end (optional) : The end index in the string where the search ends.
>>> string = 'Python strings are easy to learn.'
>>> string.count('P')
>>>string.count('P',1) #only start index provided starting at 1.
>>> string.count(' ')
>>> string.count('s',13)

8. Where is the substring?

Methods: index and find

These methods return the lowest index of the input substring in the main string (if found).

This method also requires only one parameter to run. However, it takes two optional parameters:

  • substring : The string whose count is to be found.
  • start (optional) : The start index in the string where the search starts.
  • end (optional) : The end index in the string where the search ends.
>>> string = 'Python strings are easy to learn.'
>>> string.index('P')

The difference between the two methods is that find() returns -1 if the substring is not found and index() raises a ValueError .

>>> string.find('z')
>>> string.index('z')
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
ValueError: substring not found

9. String ends with?

The endswithmethod requires only one parameter to run, however it accepts two optional parameters :

  • string : String or tuple of strings to be checked.
  • start (optional): Start index of the substring.
  • end (optional) : End index of the substring.

By default the functions takes the whole string into consideration unless one or both of start and end indices are specified.

>>> string = 'Python is fast and easy to learn.'
>>> string.endswith('to learn.')
>>> string.endswith('to learn')
>>> string.endswith('fast', 0, 14) #string[0:14]-> 'Python is fast'

To avoid confusion, we can always slice the string first instead of inputting the start and end index of the substring.

>>> string[0:14].endswith('fast')

10. String formatting

Last but not the least, the format function to inserts the variable into the placeholders of the string. The place holders are in a string are defined by curly brackets {} . If there are more than one placeholders, the values follow the order of variables in the format function.

string.format(input1, input2 .......)

Lets look at this example.

>>> x = 8
>>> y = 5
>>> string = 'The value of x is: {}.'.format(x)
>>> print(string)
The value of x is : 8.
>>> string = 'The value of x and y are: {} and {}.'.format(x,y)
>>> print(string)
The value of x and y are: 8 and 5. #follows the order of input variables.

The flower brackets {} are the placeholders.

We can also do the same thing without using the format function like this:

>>> string = f'The value of x is: {x}.'
The value of x is : 8.
>>> string = f'The value of x and y are: {x} and {y}.'
The value of x and y are: 8 and 5.

The f at the beginning of the string does the same. It takes the value of the known variable x and inputs it into the string. If the variable x is not defined before the string variable, it prints the string as it is.

The value of x is: {x}