Built-in Methods for Strings – Part2

Built-in Methods for String - Part2

In this tutorial, We will discuss about the built-in methods for strings in python. We have seen some of the built-in methods with examples in the previous tutorial. We will discuss further about other built-in methods for strings in python in detail.

isidentifier( )

The isidentifier() method is used to check if the string is a valid identifier. As we have discussed there are certain rules for identifiers which we need to follow in python. This method checks whether the string is a valid identifier according to those rules.

Syntax of isidentifier() method :

string.isidentifier( )

parameter : The isidentifier() method does not take any parameters.

return : The isidentifier() method returns True if the string is a valid identifier, otherwise it returns False.

Example :

print("valid_name : ","valid_name".isidentifier())
print("123invalid : ","123invalid".isidentifier())
valid_name :  True
123invalid :  False

islower( )

The islower() method is used to check if all the alphabets in the string are in lowercase. If all the alphabets of the string are in lowercase then it returns True, otherwise it returns False.

Syntax of islower() method :

string.islower( )

parameter : The islower() method does not take any parameters.

return : The islower() method returns True if all alphabets in a string are in lowercase, otherwise it returns False.

Example :

print("123 lower case string : ","123 lower case string".islower())
print("Not a lowercase : ","Not a lowercase ".islower())
123 lower case string :  True
Not a lowercase :  False

isupper( )

The isupper() method is used to check if all the alphabets in the string are in uppercase. If all the alphabets of the string are in uppercase then it returns True, otherwise it returns False.

Syntax of isupper() method :

string.isupper( )

parameter : The isupper() method does not take any parameters.

return : The isupper() method returns True if all alphabets in a string are in uppercase, otherwise it returns False.

Example :

print("UPPERCASE STRING : ", "UPPERCASE STRING".isupper())
print("Uppercase strring : ", "Uppercase string".isupper())
UPPERCASE STRING :  True
Uppercase strring :  False

isprintable( )

The isprintable() method is used to check if the string contains all printable characters. A printable character is one which can be printed like : alphabets and symbols, digits, white-space and punctuations. If the string contains only printable characters then it returns True, otherwise it returns False.

Syntax of isprintable() method :

string.isprintable( )

parameter : The isprintable( ) method does not take any parameters.

return : The isprintable( ) method returns True if string contains only printable characters, otherwise it returns False.

Example :

print("This is printable @1234 : ","This is printable".isprintable())
str1 = "Thiss\b is not printable"
print("string : ",str1)
print("str1 is printable ? : ",str1.isprintable())
This is printable @1234 :  True
string :  Thiss is not printable
str1 is printable ? :  False

isspace( )

The isspace() method is used to check if the string only contains white-spaces. If the string contains only white-space then it returns True, otherwise it returns False.

Syntax of isspace() method :

string.isspace( )

parameter : The isspace() method does not take any parameters.

return : The isspace() method returns True if string contains only white-space, otherwise it returns False.

Example :

print("    : ","   ".isspace() )
print("this is not space : ","This is not space".isspace())
    :  True
this is not space :  False

istitle( )

The istitle() method is used to check if the string is of the form of title. The title form means that for each word in the string first letter is capital and others are small. If the string is in specified format then it returns True otherwise it returns False.

Syntax of istitle() method :

string.istitle( )

parameter : The istitle() method does not take any parameters.

return : The istitle() method returns True if string is in title format, otherwise it returns False.

Example :

print("Title : ","Title".istitle())
print("Not title : ","Not title".istitle())
Title :  True
Not title :  False

join( )

The join() method is used to concatenate any number of strings together. It takes an iterable python object as parameter and joins all the elements of that object by inserting the string that calls join in between. Note : All the elements of the iterable object should be of string datatype only.

Syntax of join() method :

string.join(iterable)

parameter : The join() method takes an iterable python object as parameter and joins all the elements of that object.

return : The join() method returns a new string by joining all the elements of the iterable object using the string that calls join() in between.

Example :

print('_'.join(['a','b','c','1','2','3']))
print(' . '.join("string"))
print(' , '.join(('a','b',1,3)))
a_b_c_1_2_3
s . t . r . i . n . g

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 print('_'.join(['a','b','c','1','2','3']))
      2 print(' . '.join("string"))
----> 3 print(' , '.join(('a','b',1,3)))

TypeError: sequence item 2: expected str instance, int found

ljust( )

The ljust() method is used to convert the string into left justified format with the given width. This method takes a value as width of the new left justified string and another optional parameter of a character which is used to fill up the empty space after left justification.

Syntax of ljust() method :

string.ljust(width, character)

parameter : The ljust() method takes a value as width for the left justified string and an optional parameter of a character which is used to fill up the empty space after left justification of the string.

return : The ljust() method returns a new string by left justifying the string using the given width parameter.

Example :

print("Justify  : ","Jusitify".ljust(16,'%'))
print("Check me : ","Check me".ljust(15))
Justify  :  Jusitify%%%%%%%%
Check me :  Check me       

rjust( )

The rjust() method is used to convert the string into right justified format with the given width. This method takes a value as width of the new right justified string and another optional parameter of a character which is used to fill up the empty space after right justification.

Syntax of rjust() method :

string.rjust(width, character)

parameter : The rjust() method takes a value as width for the right justified string and an optional parameter of a character which is used to fill up the empty space after right justification of the string.

return : The rjust() method returns a new string by right justifying the string using the given width parameter.

Example :

print("Right Justify : ","Right Justify".rjust(20,'='))
print("New String :","New String".rjust(15))
Right Justify :  =======Right Justify
New String :      New String

lstrip( )

The lstrip() method is used to remove the extra white-spaces from the left end of the string. The lstrip method also takes an optional parameter if character which suggests to remove occurrence of this character from left end of the string.

Syntax of lstrip() method :

string.lstrip( character(optional))

parameter : The lstrip() method does not take any parameter. But it does have an optional parameter of character which suggests to remove the occurrence of that character from left end of the string.

return : The lstrip() method returns a new string by removing extra white-spaces from the left end of the string.

Example :

print("    String : ", "     String".lstrip())
print("*****Character : ","*****Character".lstrip('*'))
    String :  String
*****Character :  Character

rstrip( )

The rstrip() method is used to remove the extra white-spaces from the right end of the string. The rstrip method also takes an optional parameter if character which suggests to remove occurrence of this character from right end of the string.

Syntax of rstrip() method :

string.rstrip( character(optional))

parameter : The rstrip() method does not take any parameter. But it does have an optional parameter of character which suggests to remove the occurrence of that character from right end of the string.

return : The rstrip() method returns a new string by removing extra white-spaces from the right end of the string.

Example :

print("Right End     : ","Right End     ".rstrip())
print("Right Character))))))) : ","Right Character)))))))".rstrip(')'))
Right End     :  Right End
Right Character))))))) :  Right Character

strip( )

The strip() method is used to remove the extra white-spaces from the right end and left end of the string. The strip method also takes an optional parameter if character which suggests to remove occurrence of this character from right and left end of the string.

Syntax of strip() method :

string.strip(character(optional))

parameter : The strip() method does not take any parameter. But it does have an optional parameter of character which suggests to remove the occurrence of that character from right and left end of the string.

return : The strip() method returns a new string by removing extra white-spaces from the right and left end of the string.

Example :

print("   Strings    : ","   String   ".strip())
print("...Learn  python... : ","...Learn python...".strip('.'))
   Strings    :  String
...Learn  python... :  Learn python

maketrans( )

The maketrans() method is used to creates a one to one mapping of a character of the string to its replacement. It converts the characters of each string into unicode representation for mapping or translation. This mapping created using maketrans() method is used in translate() method for translating the string using the mapping.

Syntax of maketrans() method :

string.maketrans(dict, [ string [string] ])

parameter : The maketrans() method takes at least one parameter and optional two parameters. If only one parameter is given then it should be dictionary which should have a one-to-one mapping of string characters to its replacement. Otherwise if two parameters are given then they should be strings with equal number of characters in this case each character of first string is mapped to each character of second string. If three parameters are given then they should strings with equal number of characters

return : The maketrans() method returns a translation table or mapping which can be used in translate() method for translating the string.

Example :

dict1 = {'a':13, 'b':53, 'c':36}  # Using a dictionary
str1 = "abc"
print("String : ", str1)
print("Translation : ", str1.maketrans(dict1))
String :  abc
Translation :  {97: 13, 98: 53, 99: 36}
str1 = "abc"
str2 = "def"
str3 = "ghi"
print("Translation : ",str1.maketrans(str2, str3))
Translation :  {100: 103, 101: 104, 102: 105}
str1 = "abc"
str2 = "cde"
str3 = "efg"
str4 = "ghi"
print("Translation : ",str1.maketrans(str2, str3, str4))
Translation :  {99: 101, 100: 102, 101: 103, 103: None, 104: None, 105: None}

partition( )

The partition() method is used to divide the string into three parts. This method takes a separator as parameter, it finds the separator if found then it forms a tuple with three parts : the part before separator, the separator itself and the part after separator. Otherwise it returns the tuple with three elements first one the string itself and other two are empty strings.

Syntax of partition() method :

string.partition(separator)

parameter : The partition() method takes a separator as a parameter and divides the string in three parts by finding the separator.

return : The partition() method returns a tuple with three elements : if the separator is found then a part before separator, the separator, and part after the separator. If the separator is not found then the tuple will have the string itself as first element and two empty strings as three elements.

Example :

str1 = "Hello_World_Program"
print("string : ",str1)
print("Partition('_') : ",str1.partition('_'))
print("Partitition('.') : ",str1.partition('.'))
string :  Hello_World_Program
Partition('_') :  ('Hello', '_', 'World_Program')
Partitition('.') :  ('Hello_World_Program', '', '')

replace( )

The replace() method is used to replace all occurrences of a substring with new substring. The method takes two parameters of old substring and new substring to be replaced. It returns a new string with the replaced substring occurrences. It also has an optional parameter of count which can be used to determine how many occurrences of the substring are to be replaced.

Syntax of replace() method :

string.replace(old substring, new substring, count(optional))

parameter : The replace() method takes two strings as parameters and replaces the first substring with the second one in the original string. It also takes an optional argument of count which determines the number of occurrences to be replaced.

return : The replace() method returns the original string after replacing the old substring with new substring.

Example :

str1 = "This is a sample string."
print("Original string : ",str1)
print("Updated string : ",str1.replace("s","ht"))
print("Using optional count parameter : ",str1.replace("i","sl",2))
Original string :  This is a sample string.
Updated string :  Thiht iht a htample httring.
Using optional count parameter :  Thsls sls a sample string.

rfind( )

The rfind() method returns the index of a character or a substring given as parameter if it is found in the string. The string is searched from the right end. It returns -1 if the character or substring is not found.

Syntax of rfind() method :

string.rfind(substring)

parameter : The rfind() method takes a substring or character to find within the string as a parameter. It also takes a start or end index values as optional parameters. The start or end index values form a slice of the original string and the substring is then checked in that slice only. This method starts finding the substring form right end of the string.

return : The rfind() method returns index of first occurrence from the right if the string contains the given substring, otherwise it returns -1.

Example :

str2 = "This is a dog. What is it ?"
print("Original string : ",str2)
print("str2.rfind('is') = ",str2.rfind('is'))
print("str2[20],str2[21] - ",str2[20],str2[21])
print("str2.rfind('dog',0,6) = ",str2.rfind('dog',0,6))
print("str2[0:7] = ",str2[0:7] )
Original string :  This is a dog. What is it ?
str2.rfind('is') =  20
str2[20],str2[21] -  i s
str2.rfind('dog',0,6) =  -1
str2[0:7] =  This is

rindex( )

The index()method returns the index of a character or a substring given as parameter if it is found in the string. It raises ValueError if the character or substring is not found. This method searches for the substring from right end of the string.

Syntax of rindex() method :

string.rindex(substring)

parameter : The rindex() method takes a substring or character to find within the string as a parameter. It also takes a start or end index values as optional parameters. The start or end index values form a slice of the original string and the substring is then checked in that slice only. This method starts finding the substring form right end of the string.

return : The rindex() method returns index of first occurrence of the substring from right end of the string, if the string contains the given substring, otherwise it raises ValueError.

Example :

str_in = "Hello, how are you ? Hello, I am fine "
print("Original string : ",str_in)
print("str_in.find('Hello') = ",str_in.rindex('Hello'))
print("str_in[21],str_in[22],str_in[23],str_in[24],str_in[25] - ",str_in[21],str_in[22],str_in[23],str_in[24],str_in[25])
print("str_in.find('str',0,8) = ",str_in.rindex('str',0,8))
Original string :  Hello, how are you ? Hello, I am fine 
str_in.find('Hello') =  21
str_in[21],str_in[22],str_in[23],str_in[24],str_in[25] -  H e l l o

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

 in 
      3 print("str_in.find('Hello') = ",str_in.rindex('Hello'))
      4 print("str_in[21],str_in[22],str_in[23],str_in[24],str_in[25] - ",str_in[21],str_in[22],str_in[23],str_in[24],str_in[25])
----> 5 print("str_in.find('str',0,8) = ",str_in.rindex('str',0,8))

ValueError: substring not found

rpartition( )

The rpartition() method is used to divide the string into three parts. This method takes a separator as parameter, it finds the separator if found then it forms a tuple with three parts : the part before separator, the separator itself and the part after separator.

Otherwise it returns the tuple with three elements first two are empty strings and last one is the string itself. The main difference between partition() method and rpartition() method is that this method starts finding the separator from right end of the string.

Syntax of rpartition() method :

string.rpartition(separator)

parameter : The rpartition() method takes a separator as a parameter and divides the string in three parts by finding the separator from right end of the string.

return : The rpartition() method returns a tuple with three elements : if the separator is found then a part before separator, the separator, and part after the separator. If the separator is not found then the tuple will have two empty strings and the string itself as last element.

Example :

str1 = "Hello_World_Program"
print("string : ",str1)
print("Partition('_') : ",str1.rpartition('_'))
print("Partitition('.') : ",str1.rpartition('.'))
string :  Hello_World_Program
Partition('_') :  ('Hello_World', '_', 'Program')
Partitition('.') :  ('', '', 'Hello_World_Program')

split( )

The split() method is used to divide the string into parts using a delimiter given as parameter to the method. If there is no parameter to the method then it divides the string using white-space as delimiter. It also takes another optional parameter for maxsplits which determines the number of splits using the delimiter.

Syntax of split() method :

string.split(delimiter, maxsplits)

parameter : The split() method takes two optional parameters. The first one is the delimiter using which we split the string. If no delimiter is specified then it takes white-space as delimiter. Second parameter is maxsplit which determines the number of times we split the string.

return : The split() method returns a list with words in the string which are split using delimiter.

Example :

str1 = "This is an example"
str2 = "Learn_Python_Coding"
str3 = "Coding.in.python.is.fun"
print("String 1 : ",str1)
print("Using split() method : ",str1.split())
print("String 2 : ",str2)
print("Using split() method : ",str2.split('_'))
print("String 3 : ",str3)
print("Using split() method : ",str3.split('.',3))
String 1 :  This is an example
Using split() method :  ['This', 'is', 'an', 'example']
String 2 :  Learn_Python_Coding
Using split() method :  ['Learn', 'Python', 'Coding']
String 3 :  Coding.in.python.is.fun
Using split() method :  ['Coding', 'in', 'python', 'is.fun']

rsplit( )

The rsplit() method is used to divide the string into parts using a delimiter given as parameter to the method. If there is no parameter to the method then it divides the string using white-space as delimiter. It also takes another optional parameter for maxsplits which determines the number of splits using the delimiter. This method starts splitting the string from right end of the string.

Syntax of rsplit() method :

string.rsplit(delimiter, maxsplits)

parameter : The rsplit() method takes two optional parameters. The first one is the delimiter using which we split the string. If no delimiter is specified then it takes white-space as delimiter. Second parameter is maxsplit which determines the number of times we split the string.

return : The rsplit() method returns a list with words in the string which are split using delimiter from the right end of the original string.

Example :

str1 = "This is an example"
str2 = "Learn_Python_Coding"
str3 = "Coding.in.python.is.fun"
print("String 1 : ",str1)
print("Using rsplit() method : ",str1.rsplit())
print("String 2 : ",str2)
print("Using rsplit() method : ",str2.rsplit('_'))
print("String 3 : ",str3)
print("Using rsplit() method : ",str3.rsplit('.',3))
String 1 :  This is an example
Using rsplit() method :  ['This', 'is', 'an', 'example']
String 2 :  Learn_Python_Coding
Using rsplit() method :  ['Learn', 'Python', 'Coding']
String 3 :  Coding.in.python.is.fun
Using rsplit() method :  ['Coding.in', 'python', 'is', 'fun']

Conclusion

In this tutorial we have seen built-in methods provided by python for string objects with examples.

If you have any questions please comment below, also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment