Strings Methods in Python

String class i.e str provides many useful methods to manipulate string. In this lesson lesson we will learn some of the methods provided by str class. Specifically, we will discuss methods which does the following.

  1. Search for substring inside string
  2. Test strings
  3. Format strings
  4. Convert strings

Recall from the earlier chapter that methods are functions which belongs to an object. However, unlike function, a method are always called on a object using the following notation.

object.method_name(arg1, arg2, arg3, ...., argN)

Okay, Let's get started.

Testing Strings #

The following methods of the str class test the characters inside the string.

Method Description
str.isalnum() returns True if all the characters in the string is alphanumeric (a string which contains either number or alphabets or both). Otherwise False.
str.isalpha() returns True if all the characters in the string are alphabets. Otherwise False.
str.isdigit() returns True if all the characters in the string are digits. Otherwise False.
str.islower() returns True if all the characters in the string are in lowercase. Otherwise False.
str.isupper() returns True if all the characters in the string are in uppercase. Otherwise False.
str.isspace() returns True if all the characters in the string are whitespace characters. Otherwise False.

Here are some examples:

isalnum() method #

>>>
>>> s = "A bite of python"
>>> s.isalnum()  
False
>>>
>>> "123".isalnum()
True
>>> "abc".isalnum()
True
>>> "abc123".isalnum()
True
>>>

isalpha() method #

>>>
>>> "123".isalpha()
False
>>>
>>> "zyz".isalpha()
True
>>>
>>> "$$$$".isalpha()
False
>>>
>>> "abc233".isalpha()
False
>>>

isdigit() method #

>>>
>>>
>>> "name101".isdigit()
False
>>>
>>> "101".isdigit()
True
>>>
>>> "101 ".isdigit()
False
>>>
>>> "101.129".isdigit()
False
>>>
`

islower() and isupper() method #

>>>
>>> s
'A bite of python'
>>>
>>> s.islower()
False
>>>
>>> "abc".islower()
True
>>>
>>> s.isupper()
False
>>>
>>>
>>> "ABC".isupper()
True
>>>

isspace() method #

>>>
>>> "\n\t".isspace()
True
>>>
>>> " \n\t".isspace()
True
>>>
>>> "@ \n\t".isspace()
False
>>> "123".isspace()
False
`

Searching and Replacing Strings #

The str class has following methods which allows you to search for substrings inside a string.

Method Description
endswith(sub) Returns True if string ends with substring sub. Otherwise False.
startswith(sub) Returns True if string starts with substring sub. Otherwise False.
find(sub) Returns the lowest index of the string where substring sub is found. If substring sub is not found -1 is returned.
rfind(sub) Returns the highest index of the string where substring sub is found. If substring sub is not found -1 is returned.
count(sub) It returns the number of occurrences of substring sub found in the string. If no occurrences found 0 is returned.
replace(old, new) It returns a new string after replacing old substring with new. Notice that it does not change the object on which it is called.

Some examples:

>>>
>>> s = "abc"
>>> s.endswith("bc")
True
>>>
>>> "python".startswith("py")
True
>>>
>>> "Learning Python".find("n")
4
>>>
>>> "Learning Python".rfind("n")
14
>>>
>>> "Learning Python".find("at")
-1
>>>
>>>
>>> "procrastination is the thief of time".count("ti")
3
>>>
`
>>>
>>>
>>> s1 = "Learning C"  # old string
>>> id(s1)
49447664   # id of s1
>>>
>>> s2 = s.replace("C", "Python")   # replace() creates a new string and assigns it to s2
>>> s2  
'Learning Python'
>>>
>>> id(s1)
49447664   # notice that s1 object is not changed at all
>>>
>>>

Converting Strings #

The following methods are commonly used to return a modified version of the string.

Method Description
lower() Returns a new copy of the string after converting all of it's characters to lowercase.
upper() Returns a new copy of the string after converting all of it's characters to uppercase.
capitalize() Returns a new copy of the string after capitalizing only the first letter in the string.
title() Returns a new copy of the string after capitalizing the first letter in each word.
swapcase() Returns a new copy after converting lowercase letters to uppercase and vice-versa.
strip() Returns a new copy of the string after removing all the leading and trailing whitespace characters.
strip(chars) Returns a new copy of the string after removing chars from the beginning and end of the string.

Always remember these methods return a new string and do not modify the object upon which they are called in any way.

Here are some examples:

lower() method #

>>>
>>> "abcDEF".lower()
'abcdef'
>>>
>>> "abc".lower()
'abc'
>>>

upper() method #

>>>
>>> "ABCdef".upper()
'ABCDEF'
>>>
>>> "ABC".upper()
'ABC'
>>>

capitalize() and title() method #

>>>
>>> "a long string".capitalize()
'A long string'
>>>
>>>
>>> "a long string".title()
'A Long String'
>>>
>>>

swapcase() method #

>>>
>>> "ABCdef".swapcase()
'abcDEF'
>>>
>>> "def".swapcase()
'DEF'
>>>

strip() method #

>>>
>>> s1 = "\n\tName\tAge"
>>> print(s1)

        Name    Age
>>>
>>>
>>> s2 = s1.strip()
>>> s2
'Name\tAge'
>>> print(s2)
Name    Age
>>>
>>>

>>>
>>>
>>> s  = "--Name\tAge--"
>>>
>>> s.strip("-")
'Name\tAge'
>>>
>>>

Formatting Methods #

The following table list some formatting methods of the str class.

Method Description
center(width) Returns a new copy of the string after centering it in a field of length width.
ljust(width) Returns a new copy of the string justified to left in field of length width.
rjust(width) Returns a new copy of the string justified to right in field of length width.

center() method #

>>>
>>> "NAME".center(20)
'        NAME        '
>>>
>>>

ljust() method #

>>>
>>> "NAME".ljust(10)
'NAME      '
>>> "NAME".ljust(4)
'NAME'
>>> "NAME".ljust(5)
'NAME '
>>>

rjust() method #

>>>
>>> "NAME".rjust(10)
'      NAME'
>>>
>>> "NAME".rjust(4)
'NAME'
>>>
>>> "NAME".rjust(5)
' NAME'
>>>
>>>